2014-06-11 36 views
0

我有一個問題,從我的數據庫中刪除選定的行,事實上,我有一個C#中的窗體,其中包含一個dataGridView連接到數據庫和一個按鈕「刪除」當我點擊按鈕時,這應該刪除dataGridView和數據庫中選定行(單元格[0]和單元格[1])的信息。現在,我面臨從數據庫中刪除選定行的問題,這是我的代碼:我不能從我的數據庫中刪除信息

private void button4_Click(object sender, EventArgs e) 
     { 
      if (journalDataGridView.SelectedRows.Count == 1) 
      { 
       DataGridViewRow row = journalDataGridView.SelectedRows[0]; 
       journalDataGridView.Rows.Remove(row); 
       SqlConnection connection = new SqlConnection(connectionString); 
       connection.Open(); 
       SqlCommand sql = new SqlCommand("delete from journal where code_journal='" + journalDataGridView.CurrentRow.Cells[0].Value.ToString() + "'AND intitule='" + journalDataGridView.CurrentRow.Cells[1].Value.ToString() + "';", connection); 
       connection.Close(); 
      } 
} 

DataGridView中包含兩列 「code_journal和initule」 感謝的幫助

+0

** initule ** or ** intitule ** ?? –

+0

它是intitule @Andy G :) – Lina

回答

2

除了answer由sorton9999提供,另一個問題是你沒有做你的SqlCommand對象什麼。

創建後,您需要執行它:

SqlConnection connection = new SqlConnection(connectionString); 
connection.Open(); 
SqlCommand sql = new SqlCommand("delete from journal where code_journal='" + journalDataGridView.CurrentRow.Cells[0].Value.ToString() + "'AND intitule='" + journalDataGridView.CurrentRow.Cells[1].Value.ToString() + "';", connection); 
sql.ExecuteNonQuery(); 
connection.Close(); 

你做字符串連接打開自己最多可能的SQL注入,使用參數化查詢來代替。此外,您應該將SqlConnectionSqlCommand包含在using聲明中,以確保它們妥善處置。類似這樣的:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
    using (SqlCommand sql = new SqlCommand("delete from journal where [email protected] AND [email protected]", connection)) 
    { 
     cmd.Parameters.AddWithValue("@codeJournal", journalDataGridView.CurrentRow.Cells[0].Value.ToString()); 
     cmd.Parameters.AddWithValue("@inituleVal", journalDataGridView.CurrentRow.Cells[1].Value.ToString()); 
     connection.Open(); 
     sql.ExecuteNonQuery(); 
    } 
} 
-1

它可以像EAS y as,你的單引號(')和你的SQL語句中的AND之間沒有空格?

值得一試...

+0

感謝sorton9999你的回覆,但我仍然有同樣的問題行從dataGridView刪除,但不是從數據庫(我與本地數據庫工作) – Lina

+0

感謝你們所有人!我的問題解決了從數據庫中刪除的信息,但是當我第二次點擊顯示錶時,信息再次出現在dataGridView中(我使用綁定'MainDataSet') – Lina

5

要刪除的行,然後引用了錯誤的行與CurrentRow財產。

您也沒有使用參數來避免sql注入。

您還沒有執行命令:

DataGridViewRow row = journalDataGridView.SelectedRows[0]; 
connection.Open(); 
using (SqlCommand sql = new SqlCommand("delete from journal where [email protected]", connection)) { 
    sql.Parameters.AddWithValue("@codeJournal", row.Cells[0].Value.ToString()); 
    sql.ExecuteNonQuery(); 
} 
connection.Close(); 
journalDataGridView.Rows.Remove(row); 
相關問題