2013-02-24 55 views
0

我有我想从数据网格视图数据复制到数据库表中的数据网格视图,它抛出mysql的异常,请帮助这里是我的代码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'列'可分组可验证内容选择性公开'是错误

+0

你能在这里粘贴MySQL的例外呢? – sics 2013-02-24 14:52:10

+0

看起来像row.Cells [0] .Value是在行133无效的ID。 – sics 2013-02-24 14:53:13

+0

现在我看到没有id是133我有id到132,为什么没有循环停在132? – mani1989 2013-02-24 14:57:08

回答

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语句正确的对象处理