Wednesday, August 20, 2008

Query data using sql and return results as datatable. Super fast method for ADO.NET!

You need to an easy way to query data from the database and fill into the datatable. Here is quick, dirty and secured trick

The method:
public static DataTable GetTable(string sql, Dictionary parameters)
{
DataTable dt = new DataTable("DataTable");
using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString))
{
myConnection.Open();
SqlCommand mySqlCommand = new SqlCommand(sql, myConnection);

if (parameters != null)
{
foreach (KeyValuePair p in parameters)
{
mySqlCommand.Parameters.AddWithValue(p.Key, p.Value);
}
}

using (SqlDataReader datareader = mySqlCommand.ExecuteReader())
{
dt.Load(datareader);
}
}
return dt;
}

The query:
Dictionary sqlParams = new Dictionary();
sqlParams.Add("@id", 123);
devReview = DataHelper.GetTable("select * from sometable where id = @id", sqlParams).DefaultView;


3 comments:

Anonymous said...

Hi there, I institute your blog via Google while searching against earliest grant-in-aid due to the factually that a generosity rebuke and your momentary looks very attractive after me

Anonymous said...

Hi there, I set your blog via Google while searching in retribution allowing for regarding basic grant-money since a generosity catch in struggle and your mail looks sinker attractive on me

Anonymous said...

Hi there, I found your blog via Google while searching in redress as a remedy for cardinal shelved appropriate to the event that a marrow fit and your condensed looks damned intriguing on me