Access数据库的UPDATE查询不能正常工作C#.NET

时间:2013-04-28 14:14:46

标签: c# asp.net .net database ms-access

我正在研究数据库管理系统。我有一个更新用户配置文件的简单任务。我创建了一个带有文本框和保存按钮的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();
    }

但没有任何反应。数据库未更新。代码是否正确?

2 个答案:

答案 0 :(得分:13)

以与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不会关注参数 names ,只关注它们的顺序。

答案 1 :(得分: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);