OLEDB Excel单引号错误

时间:2011-10-18 08:15:41

标签: c# excel oledb

  

可能重复:
  OLEDB, Writing Excel cell without leading apostrophe

我正在使用此代码:

System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\test_excel.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;

sql = "CREATE TABLE EmployeeData (Id char(255), Name char(255), BirthDate date)";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();

sql = "INSERT INTO EmployeeData (Id, Name, BirthDate) values ('AAA', 'Andrew', '12/4/1955')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();

MyConnection.Close();

代码有效但我的问题是单引号(见下图)

如何解决?

example of problem http://www.freeimagehosting.net/newuploads/e32f9.jpg

2 个答案:

答案 0 :(得分:0)

您应始终使用参数化查询。它们对注射,特殊字符是安全的,并使您的代码更具可读性。

OleDbCommand cm = MyConnection.CreateCommand();
cm.CommandText = "INSERT INTO EmployeeData (Id, Name, BirthDate) values (@Id, @Name, @BirthDate)";
cm.Parameters.AddWithValue("@Id", "AAA");
cm.Parameters.AddWithValue("@Name", "'Andrew");
cm.Parameters.AddWithValue("@BirthDate", new DateTime(1955, 4, 12));
cm.ExecuteNonQuery();

答案 1 :(得分:0)

您是否尝试更改

('AAA', 'Andrew', '12/4/1955') 

进入

("AAA", "Andrew", "12/4/1955")