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)
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 row in rows)
{
foreach (var column in row)
{
Console.WriteLine(column.Key + " = " + column.Value);
}
}
}
}
No comments:
Post a Comment