使用cmd.Parameters.AddWithValue更新表值无效

时间:2016-07-11 07:11:27

标签: c# sql asp.net sql-update

如果UserId = Session["username"],我必须更新表格行中的某些值 但它显示错误:

  

ExecuteNonQuery:尚未初始化Connection属性。

任何人都可以知道我在做错了什么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();

4 个答案:

答案 0 :(得分:2)

您需要告诉SqlCommand-object使用哪个连接,更改此行

<div class="lvl1">
    <div class="lvl1.1">
        <div class="lvl1.2">
            <button class="btn-submit">Click Me</button>
            <div class="a1">Hello
        <div>
    </div>
</div>

<div class="lvl2">
    <div class="b1">
         <div class="b2">Make me disappear!</div>
    </div>
</div>

<div class="lvl3">
    <div class="c1">Thank you.
    </div>
</div>

答案 1 :(得分:1)

两个问题

  1. 在SQLCOMMAND中,您应该指定查询字符串,连接

  2. 您的更新查询语法错误

  3. ..尝试下面

    $scope.addItems = function(){
    $scope.ui = { showDiv: false ,showDiv2: true };}
    

答案 2 :(得分:0)

对所有输入使用参数,不要在查询中连接字符串。

至于您的错误,您需要指定命令需要使用的连接:

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();

答案 3 :(得分:-1)

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
'Set' Missing