我使用c#中的MySql.Data进行mysql连接。在另一个程序上它工作但目前我挂在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 :(得分: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()
}
}
}