将数据从网格视图复制到数据库表时出现mysql异常

时间:2013-02-24 14:48:32

标签: c# mysql sql winforms datagridview

我有一个数据网格视图我想将数据从数据网格视图复制到数据库表,它抛出mysql异常,请帮助这里是我的代码

     foreach (DataGridViewRow row in dataGridView2.Rows)
        {
            if (row.Cells[0].Value != null) //if id is not null
            {
                string mysqlStatement = "INSERT INTO test1(Paper, Authors, ID, GSCitations) VALUES('" + row.Cells[0].Value + "','" + row.Cells[1].Value + "','" + row.Cells[2].Value + "','" + row.Cells[3].Value + "');";
                MySqlCommand mysqlCmd = new MySqlCommand(mysqlStatement, connection);
                mysqlCmd.ExecuteNonQuery();
            }
        }

错误的整数值:第1行的“ID”列的“分组可验证内容选择性披露”错误

1 个答案:

答案 0 :(得分:0)

记录很可能包含single quote。并且您的查询易受SQL Injection攻击。

请参数化查询:

  • 避免来自SQL Injection
  • 以避免SQL Injection :D

代码snipet:

string mysqlStatement = @"INSERT INTO test1(Paper, Authors, ID, GSCitations) 
                            VALUES(@paper, @Authors, @ID, @GSCitations)";

MySqlCommand mysqlCmd = new MySqlCommand(mysqlStatement, connection);
mysqlCmd.ExecuteNonQuery();

string connStr = "connection string here";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
    using (MySqlCommand comm = new MySqlCommand())
    {
        comm.Connection = conn;
        comm.CommandText = mysqlStatement;
        comm.Parameters.AddWithValue("@paper", row.Cells[0].Value);
        comm.Parameters.AddWithValue("@Authors", row.Cells[1].Value);
        comm.Parameters.AddWithValue("@ID", row.Cells[2].Value);
        comm.Parameters.AddWithValue("@GSCitations", row.Cells[3].Value);
        try
        {
            conn.Open();
            comm.ExcuteNonQuery();
        }
        catch(MySqlException e)
        {
            // do something with
            // e.ToString()  // this is the exception
        }
    }
}

如你所见:

  • 代码使用Try-Catch块来正确处理异常
  • 使用using语句进行适当的对象处理