Monday, June 25, 2012

Enumerating the rows and columns for an arbitrary SQL query using Dapper ORM

The Dapper object-relational mapper makes it easy to execute SQL queries and manipulate the results in a .NET program. I thought it would be nice to be able to execute an arbitrary query, without knowing in advance the number, names and data types of the resulting columns, and output the results. The C# program below does exactly that.

Before using this in the real world, consider:

  • Error handling. What happens if the connection string is wrong? If the query times out? If the query returns no results? Etc.
  • Security. Do you want everyone to be able to execute any query against your database?!
  • Performance: What if someone constructs a query that takes an hour to execute?
Here's the code, which assumes you're building a C# Console Application and have added Dapper's SqlMapper.cs to the project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections;

static void Main(string[] args)
{
    string connectionString = "YOUR CONNECTION STRING GOES HERE";
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        var rows = (IEnumerable<IDictionary<string, object>>)conn.Query("ANY SQL QUERY YOU LIKE"); // e.g. select top 10 * from FooBar
        foreach (var row in rows)
        {
            foreach (var column in row)
            {
                Console.WriteLine(column.Key + " = " + column.Value);
            }
        }
    }
}

No comments:

Post a Comment