4

我正在研究数据库管理系统。我有一个更新用户配置文件的简单任务。我创建了一个带有文本框和保存按钮的 asp.net 页面。添加文本后,我单击保存按钮。按钮的代码是

protected void Button1_Click(object sender, EventArgs e)
    {
        string firstName = TextBox2.Text;
        string lastName = TextBox1.Text;
        string sCourse = TextBox3.Text;
        string sTelephone = TextBox4.Text;
        string sAddress = TextBox5.Text;
        string sEmail = TextBox6.Text;
        string Gender = TextBox7.Text;
        string user = User.Identity.Name;

        OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\ASPNetDB.accdb");
        string sqlQuerry = "UPDATE aspnet_Users SET firstName=@firstName, lastName=@lastName, Gender=@Gender, Address=@Address, Telephone=@Telephone, Course=@Course, Email=@email WHERE UserName=@UserName";

        OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);

        cmd.Parameters.AddWithValue("@UserName", User.Identity.Name);
        cmd.Parameters.AddWithValue("@firstName", firstName);
        cmd.Parameters.AddWithValue("@lastName", lastName);
        cmd.Parameters.AddWithValue("@Course", sCourse);
        cmd.Parameters.AddWithValue("@Telephone", sTelephone);
        cmd.Parameters.AddWithValue("@Address", sAddress);
        cmd.Parameters.AddWithValue("@Gender", Gender);
        cmd.Parameters.AddWithValue("@Email", sEmail);

        oleDBConn.Open();
        cmd.ExecuteNonQuery();
    }

但什么也没有发生。数据库未更新。代码是否正确?

4

2 回答 2

14

UPDATE按照与语句中出现的参数名称相同的顺序添加参数值。

cmd.Parameters.AddWithValue("@firstName", firstName);
cmd.Parameters.AddWithValue("@lastName", lastName);
cmd.Parameters.AddWithValue("@Gender", Gender);
cmd.Parameters.AddWithValue("@Address", sAddress);
cmd.Parameters.AddWithValue("@Telephone", sTelephone);
cmd.Parameters.AddWithValue("@Course", sCourse);
cmd.Parameters.AddWithValue("@Email", sEmail);
cmd.Parameters.AddWithValue("@UserName", User.Identity.Name);

带有 Access 的 OleDb 不注意参数名称,只注意它们的顺序。

于 2013-04-28T14:20:44.133 回答
3

根据查询中的顺序添加参数

  string sqlQuerry = "UPDATE aspnet_Users SET firstName=@firstName, lastName=@lastName,  Gender=@Gender, Address=@Address, Telephone=@Telephone, Course=@Course, Email=@email WHERE UserName=@UserName";

    OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@firstName", firstName);
    cmd.Parameters.AddWithValue("@lastName", lastName);
    cmd.Parameters.AddWithValue("@Gender", Gender);
    cmd.Parameters.AddWithValue("@Address", sAddress);
    cmd.Parameters.AddWithValue("@Telephone", sTelephone);
    cmd.Parameters.AddWithValue("@Course", sCourse);
    cmd.Parameters.AddWithValue("@Email", sEmail);
    cmd.Parameters.AddWithValue("@UserName", User.Identity.Name);
于 2013-04-28T14:25:46.833 回答