-1

我在 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();

谢谢你的帮助

4

1 回答 1

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()
        }
    }
}
于 2013-04-05T17:59:33.727 回答