ADO.NET数据读取封装
public class sqlserver
{
//private string sqlstr = System.ConfigurationManager.ConnectionStrings["conn03"].ConnectionString;
private string sqlstr = System.Configuration.ConfigurationManager.AppSettings["conn03"].ToString();
//返回datatable
public DataTable ExecuteDataTable(string sql,params SqlParameter[] parameters)
{
//第一步创建连接
using (SqlConnection con = new SqlConnection(sqlstr))
{
con.Open();
//实例工具
using(SqlCommand cmd = new SqlCommand (sql, con))
{
//新增参数
foreach (SqlParameter item in parameters)
{
cmd.Parameters.Add(item);
}
DataTable dt = new DataTable();
//获取数据
SqlDataAdapter dr = new SqlDataAdapter(cmd);
//填充到表
dr.Fill(dt);
return dt;
}
}
}
//返回dataset
public DataSet ExecuteDataSet(string sql,params SqlParameter[] parameters)
{
using (SqlConnection con = new SqlConnection(sqlstr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql,con))
{
foreach (SqlParameter item in parameters)
{
cmd.Parameters.Add(item);
}
DataSet ds = new DataSet ();
SqlDataAdapter dr = new SqlDataAdapter(cmd);
dr.Fill(ds);
return ds;
}
}
}
//执行增删改
public int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
{
using (SqlConnection con = new SqlConnection(sqlstr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
foreach (SqlParameter item in parameters)
{
cmd.Parameters.Add(item);
}
return cmd.ExecuteNonQuery();
}
}
}
//反回首行首列
public object ExecuScalar(string sql, params SqlParameter[] parameters)
{
using (SqlConnection con = new SqlConnection(sqlstr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
foreach (SqlParameter item in parameters)
{
cmd.Parameters.Add(item);
}
return cmd.ExecuteScalar();
}
}
}
//利用读取器来读取数据
public SqlDataReader ExecuteReader(string sql, params SqlParameter[] parameters)
{
using (SqlConnection con = new SqlConnection(sqlstr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
foreach (SqlParameter item in parameters)
{
cmd.Parameters.Add(item);
}
return cmd.ExecuteReader();
}
}
}
}