c# MySql.数据插入错误
本文关键字:错误 插入 数据 MySql | 更新日期: 2023-09-27 18:07:55
我使用MySql。mysql连接的c#数据。在另一个程序中,它工作,但目前我挂在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();
感谢您的帮助
KEY
是mysql中的保留关键字。应该使用反打号,
INSERT INTO jt_teamsync (`key`) VALUES(...)
- MySQL保留关键词列表
作为旁注,您的查询非常弱。它易受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()
}
}
}