2013-04-05 77 views
-1

我在c#中使用MySql.Data作为mysql连接。在另一个程序工作,但目前我挂在INSERT INTO命令。C#MySql.Data INSERT INTO错误

我得到以下错误:

An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll 
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key) VALUES ('PGJWZBPOWTRPUTKY')' at line 1 

有了这个代码:

MySqlCommand Command = Connection.CreateCommand(); 
     MySqlDataReader Reader; 
     Command.CommandText = "INSERT INTO jt_teamsync (key) VALUES ('" + TeamSyncKey + "')"; 
     Connection.Open(); 
     Reader = Command.ExecuteReader(); 
     Connection.Close(); 

感谢所有帮助

+0

该错误.. key'也是什么是'一个字段name..if所以为什么不''别名'表名'插入jt_teamsync J(j.key)VALUES(''+ TeamSyncKey +'')“;''例如 – MethodMan 2013-04-05 18:04:01

回答

3

KEY是MySQL中的保留关键字。应该使用反引号转义,

INSERT INTO jt_teamsync (`key`) VALUES(...) 

一点题外话,您的查询是非常弱的。这是易受伤害的SQL Injection。参数从我在看如果不告诉你的直接错误是什么几乎以避免它的价值,如

string content = TeamSyncKey; 
string connStr = "connection string here"; 
string sqlStatement = "INSERT INTO jt_teamsync (`key`) VALUES (@key)"; 
using (MySqlConnection conn = new MySqlConnection(connStr)) 
{ 
    using(MySqlCommand comm = new MySqlCommand()) 
    { 
     comm.Connection = conn; 
     comm.CommandText = sqlStatement; 
     comm.CommandType = CommandType.Text; 

     comm.Parameters.AddWithValue("@key", content); 

     try 
     { 
      conn.Open(); 
      comm.ExecuteNonQuery(); 
     } 
     catch(MySqlException e) 
     { 
      // do something with the exception 
      // do not hide it 
      // e.Message.ToString() 
     } 
    } 
} 
+0

感谢它的工作。我之前用'而不是'尝试过,但它不会工作。 – 2013-04-05 18:03:23

+0

不客气':D' – 2013-04-05 18:06:25

+0

是的,因为单引号是用于字符串文字的。表名和列名都是标识符。 – 2013-04-05 18:16:34