我在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 :(得分: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
}
}
答案 1 :(得分: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();
答案 2 :(得分:0)
假设连接已经打开,在你的while循环中你缺少以下语句:
cmd3.ExecuteNonQuery();
您必须执行该命令才能更新数据库。