我正在尝试将我的数据从webservice更新到我的数据库。但是,一旦我在Web服务页面中单击调用,并运行此命令:“command1.Connection.Open();”我将收到此错误消息:对象引用未设置为对象的实例。
这是我的代码:
[WebMethod]
public void UpdateParticulars(string Name, string CLass, string NRIC, float AmountSpent)
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ncpConnectionString2"].ConnectionString))
{
SqlCommand command1 = new SqlCommand("UPDATE Student set Name=@Name, Class=@CLass,StallNo=@StallNo,AmountSpent=@AmountSpent WHERE NRIC = '" + NRIC + "'");
command1.Parameters.AddWithValue("@Name", Name);
command1.Parameters.AddWithValue("@Class", CLass);
command1.Parameters.AddWithValue("@NRIC", NRIC);
command1.Parameters.AddWithValue("@AmountSpent", AmountSpent);
command1.Connection.Open();
command1.ExecuteNonQuery();
}
}
答案 0 :(得分:8)
将SqlConnection
作为参数传递给SqlCommand
构造函数。
SqlCommand command1 = new SqlCommand(query, conn);
同时将您的查询更改为完全参数化(并且您缺少@StallNo参数):
"UPDATE Student set Name=@Name, Class=@CLass,StallNo=@StallNo,AmountSpent=@AmountSpent WHERE NRIC = @NRIC"
command1.Parameters.AddWithValue("@Name", Name);
command1.Parameters.AddWithValue("@Class", CLass);
command1.Parameters.AddWithValue("@NRIC", NRIC);
command1.Parameters.AddWithValue("@AmountSpent", AmountSpent);
command1.Parameters.AddWithValue("@StallNo", ""); //missing parameter
答案 1 :(得分:0)
使用command1.Connection = conn; conn.Open();
在执行ExecuteNonQuery()之前
答案 2 :(得分:0)
只需添加此行
即可conn.open();
而不是
command1.Connection.Open();