public class LoadDataset
{
public DataSet GetAllData(string sp)
{
return LoadSQL(sp);
}
private DataSet LoadSQL(string sp)
{
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand(sp, con);
DataSet ds;
try
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
finally
{
con.Dispose();
cmd.Dispose();
}
}
}
Refactorings
No refactoring yet !
Ants
June 3, 2010, June 03, 2010 00:36, permalink
Take advantage of the 'using' keyword. Check out the sample code under the docs for SqlDataReader:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
For your code, just replace the sample's while loop, with your DataTable creation and Load() call.
Kathy Wu
June 3, 2010, June 03, 2010 02:32, permalink
public class LoadDataset
{
public static DataSet Load(string sp)
{
DataSet ds = new DataSet();
using (SqlConnection conn = CreateConnection())
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sp, conn);
da.Fill(ds, "myDataSet");
}
return ds;
}
private static SqlConnection CreateConnection()
{
return new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
}
}
i try to write a winform application:
i dislike below codes:
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
<b>Above part of codes looks unsufficient.How can i best loading dataset?</b>