Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple SQL statements in one roundtrip using Dapper.NET

There is a nice feature in ADO.NET that allows you to send multiple SQL statements to database in one roundtrip and receive results for all statements:

var command = new SqlCommand("SELECT count(*) FROM TableA; SELECT count(*) FROM TableB;", connection);  using(var reader = command.ExecuteReader()) {     reader.Read();     resultA = reader.GetInt32(0);     reader.NextResult();     reader.Read();     resultB = reader.GetInt32(0); } 

Is there a similar feature in Dapper.NET?

like image 552
user1224129 Avatar asked Oct 12 '13 18:10

user1224129


People also ask

How do I run multiple SQL statements at once?

To run a query with multiple statements, ensure that each statement is separated by a semicolon; then set the DSQEC_RUN_MQ global variable to 1 and run the query. When the variable is set to zero, all statements after the first semicolon are ignored.

Does Dapper handle SQL injection?

Dapper has great performance because it doesn't translate queries that we write in . NET to SQL. It is important to know that Dapper is SQL Injection safe because we can use parameterized queries, and that's something we should always do. One more important thing is that Dapper supports multiple database providers.

What is splitOn in Dapper?

splitOn: CustomerId will result in a null customer name. If you specify CustomerId,CustomerName as split points, dapper assumes you are trying to split up the result set into 3 objects. First starts at the beginning, second starts at CustomerId , third at CustomerName . Follow this answer to receive notifications.


2 Answers

Yes, the Dapper QueryMultiple extension can do that:

string query = @"SELECT COUNT(*) FROM TABLEA;                  SELECT COUNT(*) FROM TABLEB"; using (var multi = connection.QueryMultiple(query, null)) {     int countA = multi.Read<int>().Single();     int countB = multi.Read<int>().Single(); }      

According to Marc Gravell this is the ideal way to execute multiple queries in a single batch.

Note: Dapper creator Sam Saffron has posted a detailed explanation with code sample on using QueryMultiple to accomplish this.

UPDATE: I add the important comment from Marc

Note: from 1.5-ish (a little earler on the alpha builds) there is a ReadSingle() method that may be more convenient and efficient than Read().Single()

like image 142
Steve Avatar answered Sep 23 '22 05:09

Steve


var grid = connection.QueryMultiple("              SELECT COUNT(*) FROM TABLEA              SELECT COUNT(*) FROM TABLEB              SELECT COUNT(*) FROM TABLEC"); var lstResult = new List<int>(); var isNext = false; do{     var first2 = info.Read<int>().Single();     lstResult.Add(first2);     isNext=info.IsConsumed; } while (!isNext); 
like image 33
Ahmad Aghazadeh Avatar answered Sep 20 '22 05:09

Ahmad Aghazadeh