2016-07-04 117 views
0

我寫在asp.net這個代碼,但它仍然不是在一個SQL Server數據庫中更新記錄:如何通過asp.net更新SQL Server數據庫中的記錄?

SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn); 
SqlDataReader dr = cmd4.ExecuteReader(); 

while (dr.Read()) 
    SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " ' where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+  "' ", conn); 
+0

我不認爲這甚至編譯,因爲一個聲明不能的身體控制流程塊沒有括號。另外你試圖達到什麼目標?你爲什麼要做'SELECT'查詢然後忽略結果? –

+0

它編譯成功,但不更新,我使用select查詢爲了讀取行並根據條件更新指定的列。 –

+0

您問題中的代碼將無法成功編譯。粘貼時要精確。 –

回答

0

假設的連接已經打開,在你的while循環你缺少以下語句:

cmd3.ExecuteNonQuery(); 

您必須執行該命令才能更新數據庫。

2

使用ado.net有道:

var newId = count + 1; 
var roomType = typeRadioButtonList1.SelectedItem.ToString(); 

using (var connection = new SqlConnection("your db connection string here")) 
{ 
     var query = "UPDATE [roomdetail] SET [rid] = @rid WHERE [rid] = 0 AND roomtype = @roomType"; 

     SqlCommand command = new SqlCommand(query, connection); 
     command.Parameters.AddWithValue("@rid", newId); 
     command.Parameters.AddWithValue("@roomType", roomType); 

     try 
     { 
      command.Connection.Open(); 
      command.ExecuteNonQuery(); 
     } 
     catch (Exception ex) 
     { 
      //handle exception 
     } 
} 
+2

實際上,*真正*適當的方法是將'SqlCommand'放入'using(...){....}'塊中! –

1

你缺少ExecuteNonQuery方法下面寫代碼

SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn); 
SqlDataReader dr = cmd4.ExecuteReader(); 

while (dr.Read()) 
SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " ' where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+  "' ", conn); 
cmd3.executeNonQuery(); 
相關問題