为什么我在此更新语句中遇到语法错误?

Ari*_*eah 2 c# oledb ms-access syntax-error sql-update

我想更新我的 m/s access 数据库中的一张表,其中我的用户输入了新密码以替换旧密码,但更新语句中存在语法错误。请帮忙!

public partial class resetPassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            string userName = (string) Session["username"];

        string str = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\JetStar\database\JetstarDb.accdb";
        var con = new OleDbConnection(str);
        con.Open();

        string pwd = Request.Form["conPassword"];
        OleDbCommand cmd = new OleDbCommand("UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'", con);

        try
        {
            cmd.ExecuteNonQuery();
            MessageBox.Show("Your password has been changed successfully."); 
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Son*_*nül 5

发生这种情况可能是因为password是Microsoft Access 上的保留关键字。您应该将其与方括号一起使用,如下所示[password]

但更重要的是

您应该始终使用参数化查询。这种字符串连接容易受到SQL 注入攻击。

不要将您的密码存储为纯文本。阅读:在数据库中存储密码的最佳方法

使用using语句来处理你的OleDbConnectionand OleDbCommand

using(OleDbConnection con = new OleDbConnection(str))
using(OleDbCommand cmd = con.CreateCommand())
{
    cmd.CommandText = "UPDATE [users] SET [password] = ? WHERE username = ?";
    cmd.Parameters.Add("pass", OleDbType.VarChar).Value = pwd;
    cmd.Parameters.Add("user", OleDbType.VarChar).Value = userName;
    con.Open();
    try
    {
        cmd.ExecuteNonQuery();
        MessageBox.Show("Your password has been changed successfully."); 
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)