- Dapper updates use the
Execute()method to runUPDATESQL statements and return the number of affected rows. - A
WHEREclause is mandatory, otherwise every row in the whole table will get updated! - Not recommended: building SQL via string concatenation (the naive approach shown), which carries a SQL injection vulnerability.
- 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
UPDATESQL and add aWHEREclause 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)
- The WHERE clause is absolutely required
OmitWHERE→UPDATE student SET xxx, this modifies every row in the table and causes serious data loss. - Strict parameter name matching
Case does not matter between@ParameterNamein SQL and entity / anonymous‑class properties, but names must match exactly. - Meaning of return value
int rowsAffected: value greater than zero means rows were updated; zero means no matching records found. - 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
Previous: Insert
Next: Dapper delete operation