2

i am trying to update my data from webservice to my database. But once i click invoke in the web service page , and run to this command:"command1.Connection.Open();" i will receive this error message :Object reference not set to an instance of an object.

this is my code:

  [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();
            }
        }
4

3 回答 3

8

将您的SqlConnectionas 参数传递给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
于 2013-07-26T07:04:02.283 回答
0

使用 command1.Connection=conn; conn.Open();

在执行 ExecuteNonQuery() 之前

于 2013-07-26T07:15:54.630 回答
0

只需添加这一行

conn.open();

代替

command1.Connection.Open();
于 2013-07-26T07:17:53.180 回答