2016-07-04 108 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(); 
相关问题