Update operation

  1. Dapper updates use the Execute() method to run UPDATE SQL statements and return the number of affected rows.
  2. A WHERE clause is mandatory, otherwise every row in the whole table will get updated!
  3. Not recommended: building SQL via string concatenation (the naive approach shown), which carries a SQL injection vulnerability.
  4. Recommended: parameter‑based queries with @ParameterName, paired with entity or anonymous classes for automatic parameter mapping.

Original note: The update workflow is similar to inserts; write your UPDATE SQL and add a WHERE clause so only target rows get modified.

Example

// Dangerous code! String concatenation opens SQL injection risks, for bad‑practice demonstration only
using (IDbConnection db = new MySqlConnection(conn))
{
    var id = 1;
    string sqlUpdate = "UPDATE student set FirstName='NewName',LastName='NewSurname',Email='NewEmail' WHERE Id=" + id;
    int rows = db.Execute(sqlUpdate);
    var info = db.Query<Student>("Select * From student WHERE Id=" + id, new { id }).SingleOrDefault();
}Code language: C# (cs)

Standard Parameterized Implementation

using System.Data;
using MySql.Data.MySqlClient;
using Dapper;
using System.Configuration;

static void Main(string[] args)
{
    var conn = ConfigurationManager.ConnectionStrings["StudentConnection"].ConnectionString;
    using (IDbConnection db = new MySqlConnection(conn))
    {
        // 1.Update SQL with @ parameter placeholders
        string sqlUpdate = @"UPDATE student 
                             SET FirstName=@FirstName, LastName=@LastName, Email=@Email 
                             WHERE Id=@Id";

        // 2.Prepare update payload using an entity object
        var stu = new Student()
        {
            Id = 1,
            FirstName = "foxdevelop",
            LastName = "com",
            Email = "admin@foxdevelop.com"
        };

        // 3.Run update and get affected row count
        int rowsAffected = db.Execute(sqlUpdate, stu);

        // 4.Query to verify update result
        var studentInfo = db.Query<Student>(
            "SELECT * FROM student WHERE Id=@Id",
            new { Id = 1 }
        ).SingleOrDefault();
    }
    Console.ReadKey();
}

// Student entity class
public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}Code language: C# (cs)
  1. The WHERE clause is absolutely required
    Omit WHEREUPDATE student SET xxx, this modifies every row in the table and causes serious data loss.
  2. Strict parameter name matching
    Case does not matter between @ParameterName in SQL and entity / anonymous‑class properties, but names must match exactly.
  3. Meaning of return value
    int rowsAffected: value greater than zero means rows were updated; zero means no matching records found.
  4. Security note
    Never concatenate raw strings to build SQL. User‑supplied input can trigger SQL injection attacks.

Partial‑field Only Update

If you only want to change the email address, you do not need to list every column:

UPDATE student SET Email=@Email WHERE Id=@Id

Update operation

Leave a Reply

Your email address will not be published. Required fields are marked *