public static class SqlHelper
{
//获取连接字符串
private static readonly string constr = ConfigurationManager.ConnectionStrings["connectionStr"].ConnectionString;
//ExecuteNonQuery()方法
//ExecuteScalar()方法
//ExecuteReader()方法
//ExecuteDataTable()方法
//执行增删改的
public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
{
//使用using关键字定义一个范围,在范围结束时自动调用这个类实例的Dispose处理对象
using (SqlConnection con = new SqlConnection(constr))
{
//创建执行sql命令对象
using (SqlCommand cmd = new SqlCommand(sql, con))
{
//判断是否传递了sql参数
if (pms != null)
{
//将参数添加到Parameters集合中
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
//执行返回单个值的
public static object ExecuteScalar(string sql, params SqlParameter[] pms)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteScalar();
}
}
}
//执行返回SqlDataReader
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
{
SqlConnection con = new SqlConnection(constr);
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
try
{
con.Open();
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
con.Close();
con.Dispose();
throw;
}
}
}
//执行返回DataTable
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms)
{
DataTable dt = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, constr))
{
if (pms != null)
{
adapter.SelectCommand.Parameters.AddRange(pms);
}
adapter.Fill(dt);
}
return dt;
}
public static DataSet Query(string SQLString,params SqlParameter[] pms)
{
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(SQLString, constr))
{
if (pms != null)
{
adapter.SelectCommand.Parameters.AddRange(pms);
}
adapter.Fill(ds);
}
return ds;
}
}
本文出自 “风中寻觅” 博客,请务必保留此出处http://xingcheng.blog.51cto.com/3693811/1741849
原文地址:http://xingcheng.blog.51cto.com/3693811/1741849