Execute sql statement and get datareader - WITH flow control
I have a standard method which gets some data from SQL Server. I want to refactor this so that based on the value of an enum (pas开发者_StackOverflow中文版sed as a method parameter), a different sql statement is executed (all return datareader).
I can't seem to code this in a way which is elegant and tidy. What would be a good way to do this?
Thanks
I have quite a few of these kind of things in my projects, a short example:
enum QueryType {AQuery, BQuery};
private SqlDataReader DoQuery(QueryType _type)
{
using (SqlConnection conn = new SqlConnection("your connection string"))
{
using (SqlCommand cmd = conn.CreateCommand())
{
switch(_type)
{
case QueryType.AQuery:
cmd.CommandText = @"SELECT thing FROM table";
break;
case QueryType.BQuery:
cmd.CommandText = @"SELECT other_thing FROM table";
break;
}
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
//...
}
}
}
Something like this perhaps?
// delegate to use for adding parameters
delegate void AddParametersDelegate(IDbCommand cmd);
IDataReader GetReader(SomeEnumType val, AddParametersDelegate addParms)
{
string sql = null;
switch (val)
{
case EnumVal1:
sql = "SQL Statement 1";
break;
case EnumVal2:
sql = "SQL Statement 2";
break;
.
default:
sql = "Default SQL Statement";
break;
}
using (IDbConnection conn = CreateDBConnection(connString))
{
using (IDbCommand cmd = conn.CreateCommand(sql))
{
// call the delegate to add the parameters to the SQL command
addParams(cmd);
return cmd.ExecuteReader(sql);
}
}
}
精彩评论