代码之家  ›  专栏  ›  技术社区  ›  Pankaj

更新语句中的问题

  •  0
  • Pankaj  · 技术社区  · 5 年前

    我正在编写以下几行代码来更新access数据库中的数据。

    using (OleDbConnection con = new OleDbConnection())
    {
        con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
        con.Open();
    
        using (OleDbCommand cmd = new OleDbCommand())
        {
            cmd.Connection = con;
            cmd.CommandText = "update tblusers set password = @password where userId = @userId;";
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Parameters.AddWithValue("@userId", authResult.UserId);
            cmd.Parameters.AddWithValue("@password", newPassword);
            cmd.ExecuteNonQuery();
        }
    }
    

    当这条线运行时 cmd.ExecuteNonQuery(); 我得到了以下错误:

    UPDATE语句语法错误

    更新-2

    using (OleDbConnection con = new OleDbConnection())
    {
        con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
        con.Open();
        using (OleDbCommand cmd = new OleDbCommand())
        {
            cmd.Connection = con;
            cmd.CommandText = "update tblusers set password = ? where userId = ?;";
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Parameters.Add("p1", OleDbType.VarChar, 100).Value = newPassword;
            cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
            cmd.ExecuteNonQuery();
        }
    }
    
    1 回复  |  直到 5 年前
        1
  •  3
  •   marc_s MisterSmith    5 年前

    首先:MS Access/OleDB可以 命名 位置的 参数。所以 其中你指定的参数是非常相关的!

    ? 作为参数占位符。

    using (OleDbCommand cmd = new OleDbCommand())
    {
        cmd.Connection = con;
        cmd.CommandText = "update tblusers set [password] = ? where userId = ?;";
        cmd.CommandType = System.Data.CommandType.Text;
    
        // parameters - do *NOT* use "AddWithValue", and specify in the *correct order*!
        // since the parameters are *positional*, the name provided is irrelevant
        cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = newPassword;
        cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
    
        cmd.ExecuteNonQuery();
    }
    
    推荐文章