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 に答える