一、DataAdapter
获取数据库数据最常用的办法是使用DataAdapter然后填充到DataSet中。
代码如下:
public static DataSet SelectData( )
{
string connection = "server=.;uid=user;pwd=111;connect timeout=10";
SqlConnection sc = new SqlConnection(connection);
sc.Open();
SqlCommand cmd = new SqlCommand("Select * From c where id=1", sc);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
return ds;
}
也可以直接简写如下:
public DataSet SelectData()
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From c where id=1", "server=.;uid=user;pwd=111");
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
return ds;
}
二、DataReader
DataReader数据可以转化为各种类型输出,如List,Dictionary,DataTable等,下面的代码例子是转化为字典输出
public static IDictionary SelectData()
{
string connection = "server=.;uid=user;pwd=111";
SqlConnection sc = new SqlConnection(connection);
sc.Open();
SqlCommand cmd = new SqlCommand("Select * From c where id=1", sc);;
SqlDataReader reader = cmd.ExecuteReader();
IDictionary dict = null;
if (reader.Read())
{
int fieldCount = reader.FieldCount;
dict = new SortedList(fieldCount);
for (int i = 0; i < fieldCount; i++)
dict[reader.GetName(i).ToLower()] = reader.GetValue(i);
}
reader.Close();
reader.Dispose();
return dict;
}