2013-02-24 59 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語句正確的對象處理