您好,登录后才能下订单哦!
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;
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。