如何通过asp.net更新SQL Server数据库中的记录
本文关键字:数据库 记录 Server SQL 何通过 asp net 更新 | 更新日期: 2023-09-27 17:54:55
我在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);
使用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
}
}
您缺少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();
假设连接已经打开,在while循环中您将缺少以下语句:
cmd3.ExecuteNonQuery();
您必须执行命令才能更新数据库。