使用 cmd.Parameters.AddWithValue 更新表值不起作用
本文关键字:不起作用 更新 AddWithValue cmd Parameters 使用 | 更新日期: 2023-09-27 17:56:12
如果UserId
= Session["username"]
,我必须更新表行中的一些值但它显示的错误:
执行非查询:连接属性尚未初始化。
任何人都可以知道我在这里做错了什么Session["username"]
我检查过它的价值。
SqlConnection conn7 = new SqlConnection(@"Data Source=SANJAY-PC'SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa@123;Pooling=False");
var qry = "UPDATE Registration (FirstName,LastName,Password,LastName,EmaildId,UserId) " +
"VALUES (@FirstName, @LastName, @Password, @EmaildId, @UserId) WHERE UserId='" + Session["username"] + "'";
var cmd = new SqlCommand(qry);
cmd.Parameters.AddWithValue("@FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("@LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("@Password", Password_Update.Text);
cmd.Parameters.AddWithValue("@EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("@UserId", UserIdUpdate.Text);
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
你需要告诉 SqlCommand 对象使用哪个连接,更改此行
var cmd = new SqlCommand(qry, conn7);
两个问题
-
在SQL命令中,您应该指定查询字符串,连接
-
更新查询语法错误
..在下面尝试
SqlConnection conn7 = new SqlConnection(@"Data Source=SANJAY-PC'SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa@123;Pooling=False");
var qry = "UPDATE Registration
SET FirstName=@FirstName,LastName=@LastName,Password=@Password,
EmaildId=@EmaildId,UserId=@UserId WHERE UserId=@UserId1";
var cmd = new SqlCommand(qry,conn7);
cmd.Parameters.AddWithValue("@FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("@LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("@Password", Password_Update.Text);
cmd.Parameters.AddWithValue("@EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("@UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("@UserId1", Session["username"].ToString());
conn7.Open();
// cmd7.ExecuteNonQuery();
cmd.ExecuteNonQuery();
conn7.Close();
对所有输入使用参数,不要在查询中连接字符串。
至于您的错误,您需要指定命令需要使用的连接:
SqlConnection conn7 = new SqlConnection(@"Data Source=SANJAY-PC'SQLEXPRESS;
Initial Catalog=dev;User ID=sa;Password=sa@123;Pooling=False");
var qry = " UPDATE Registration SET FirstName = @FirstName, LastName = @LastName,"
+ " Password = @Password, EmaildId = @EmaildId WHERE UserId = @UserCondition";
var cmd = new SqlCommand(qry, conn7 );
cmd.Parameters.AddWithValue("@FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("@LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("@Password", Password_Update.Text);
cmd.Parameters.AddWithValue("@EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("@UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("@UserCondition", Session["username"].ToString());
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
'Set' Missing