简体   繁体   English

无法将数据更新到SQL表中

[英]Unable to update data into SQL table

I got a question. 我有一个问题。 When I put this code 当我把这个代码

protected void Page_Load(object sender, EventArgs e)
{
    string email = Membership.GetUser(User.Identity.Name).Email;
    MembershipUser currentUser = Membership.GetUser();
    string UserId = currentUser.ProviderUserKey.ToString();

    **TextBox2.Text = email;
    TextBox3.Text = UserId;**
}

My data will not be saved to the database. 我的数据不会保存到数据库中。

 {
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
    SqlCommand cmd = new SqlCommand("UPDATE aspnet_Membership SET Email = @email WHERE UserId = @id1", conn);

    cmd.Connection = conn;
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@email", TextBox2.Text);
    cmd.Parameters.AddWithValue("@id1", TextBox3.Text);
    try
    {
        conn.Open();
        cmd.ExecuteNonQuery();

    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        conn.Close();
    }

But when I removed 但是当我删除

 **TextBox2.Text = email;
TextBox3.Text = UserId;**

The data will be saved into database using above code. 使用上面的代码将数据保存到数据库中。 Can someone tell me why? 有人可以告诉我为什么吗? Thanks in advance. 提前致谢。

Given you never execute the command I can't explain it. 鉴于你永远不会执行命令,我无法解释它。

Add

 
 
 
  
  cmd.ExecuteNonQuery();
 
  

To the end of your click method 到您的点击方法结束

Because you are setting the values in your page load event, they are overwriting the changed values in the controls when your button on postback. 因为您在页面加载事件中设置值,所以当回发按钮时,它们会覆盖控件中更改的值。 Wrap your page load code with a 用一个包装你的页面加载代码

 if (!Page.IsPostback) { string email = Membership.GetUser(User.Identity.Name).Email; MembershipUser currentUser = Membership.GetUser(); string UserId = currentUser.ProviderUserKey.ToString(); TextBox2.Text = email; TextBox3.Text = UserId; } 

You are never executing your SQL so I'm very surprised that your DB is updating at all. 你永远不会执行你的SQL,所以我很惊讶你的数据库正在更新。

Take a look at the ExecuteNonQuery method. 看一下ExecuteNonQuery方法。 With your current query you are creating a SQLCommand and then never running the SQL. 使用当前查询,您将创建一个SQLCommand,然后从不运行SQL。

Try the following 请尝试以下方法

cmd.Connection = conn;
cmd.Connection.Open()

after you assign it and then 分配之后再分配

cmd.ExecuteNonQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM