2013-04-05 103 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