0

我有一个数据网格视图我想将数据从数据网格视图复制到数据库表,它会引发 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”列的“分组可验证内容选择性披露”是错误的

4

1 回答 1

0

记录很有可能包含single quote. 并且您的查询很容易受到SQL Injection.

请参数化查询:

  • 避免SQL Injection
  • 避免SQL Injection :D

代码片段:

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语句进行正确的对象处理
于 2013-02-24T14:55:46.627 回答