C#编程sql语句反斜杠问题
折腾了一下午,外加半个晚上,终于把数据从局域网内的服务器调出来了!
问题是这样的,通过Oracle Sql Developer,我把数据表ChemicalComposition建立在隔壁小浩的Oracle服务器上,然后我这台客户机上想利用C#程序调用其中的ChemicalComposition。
关键代码片段如下
using (OracleConnection AGConnection = new OracleConnection(connectionString))
{
OracleCommand AGCommand = AGConnection.CreateCommand();
AGCommand.CommandText = "SELECT * FROM ""ChemicalComposition""";
OracleDataAdapter dataAdapter = new OracleDataAdapter(AGCommand);
dataAdapter.Fill(AlloyGradeTable);
} // AGConnection.Dispose called automatically.
其实这段代码拷到网页页面上有点失真,
AGCommand.CommandText = "SELECT * FROM ""ChemicalComposition""";
在Visual Studio中是:
AGCommand.CommandText = "SELECT * FROM \"ChemicalComposition\"";
下午一直用 "SELECT * FROM ChemicalComposition"做程序中的查询语句,结果报错为:
ORA-00942: table or view does not exist
老是以为数据库连接有错,根本就没有考虑sql语句出错!
如果在Oracle Sql Developer使用SELECT * FROM ChemicalComposition,结果报错为:
An error was encountered performing the requested operation:
ORA-00942: table or view does not exist
00942. 00000 - "table or view does not exist"
*Cause:
*Action:
Error at Line:1 Column:14
到晚上才明白,sql语句有错,因为之前也知道在 Oracle Sql Developer中sql语句的表名是要加双引号的,就是说使用SELECT * FROM "ChemicalComposition"可以从数据库中成功地调出数据。
很好,问题的根源找到,那么怎么在C#程序中写sql语句呢?一开始我写成:
AGCommand.CommandText = "SELECT * FROM ""ChemicalComposition""";
当然是行不通的,该错误Visual Studio轻易捕获,接着有改成:
AGCommand.CommandText = "SELECT * FROM " + ""ChemicalComposition"" + """;
还是不行,通不过!
后来在网上一顿猛搜,原来在字符串中的双引号"要用反斜杠加双引号\"表示!我靠!这个不是在C语言中学过么???真是个极其弱智的问题!
这种问题在用C语言编程时就碰到过,为何到C#中却不加注意?这是经验不足么?还是缺乏变通能力?