c# - updating sql server database using c# in asp.net
问题描述
There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?
protected void Page_Load(object sender, EventArgs e) {
rno.Text = Request.QueryString["rno"];//rno is a textbox
string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "select fname from table1 where rno = @rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("@rno", rno.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()) {
fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
}
reader.Close();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
protected void modify_Click(object sender, EventArgs e) {
fName.ReadOnly = false;
}
protected void savechanges_Click(object sender, EventArgs e) {
string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update table1 set fname=@fname where rno = @rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("@fname", sfname);
command.Parameters.AddWithValue("@rno", rno.Text.Trim());
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
解决方案
我已经尝试过您的代码,该代码也执行得很好并且更新了数据库表。
我试过如下:
string connectionString = @"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update TestTable set fname=@fname where rno =rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("@fname", "Test");
command.Parameters.AddWithValue("@rno", "rno");
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
我尝试过的另一种方法。
using (SqlConnection connection = new SqlConnection(connectionString ))
{
connection.Open();
var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";
using (SqlCommand cmd = new SqlCommand(queryText, connection))
{
responseResults = await cmd.ExecuteNonQueryAsync();
}
connection.Close();
}
希望它会有所帮助
推荐阅读
- amazon-ec2 - 如何在 Lambda 中从警报中提取特定信息(如实例 ID)(使用成本指标)
- vb.net - VB.NET Docker 失败
- sql - 撤消 COPY 命令 redshift | 从红移中删除
- c++ - 如何组合具有相同代码的两个模板函数?
- docker - 将 GCP 永久磁盘挂载为 NFS
- mysql - 如何使用 wamp 在本地访问我的 react js 应用程序并允许访问其他计算机?
- r - 循环数据帧以模拟正常的数据分布
- wordpress - WordPress如何重定向私人自定义帖子类型
- java - Java listIterator - 我如何让它只迭代一次?
- kotlin - Swagger 不包含 import kotlinx.serialization.Serializable 到生成的类中