Executing Non Query Commands With Dapper

Dapper provides the Execute method (and its async equivalent) for commands that are not intended to return resultsets i.e. INSERT, UPDATE and DELETE commands. The Execute method returns an int, representing the number of rows affected by the successful completion of the command.

Insert

var sql = "insert into categories (CategoryName) values ('New Category')";
using (var connection = new SQLiteConnection(connString))
{
    var affectedRows =  connection.Execute(sql);
    Console.WriteLine($"Affected Rows: {affectedRows}");
}

Image

Update

var sql = @"update products set unitprice = unitprice * .1 where categoryid = 2";
using (var connection = new SQLiteConnection(connString))
{
    var affectedRows = connection.Execute(sql);
    Console.WriteLine($"Affected Rows: {affectedRows}");
}

Image

Delete

var sql = "delete from categories where CategoryName = 'New Category'";
using (var connection = new SQLiteConnection(connString))
{
    var affectedRows =  connection.Execute(sql);
    Console.WriteLine($"Affected Rows: {affectedRows}");
}

Image

Last updated: 21/05/2019 13:53:15