public class SqlHlper
{
public static readonly string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
//执行增删改
public static object ExecuteNonQuery(string sql, params SqlParameter[] pms)//SqlParameter需要调用Data.SqlClient
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
//获取单个数据
public static object ExecteScalar(string sql, params SqlParameter[] pms)
{
object obj = null;
using (SqlConnection conn = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
obj = cmd.ExecuteScalar();
}
return obj;
}
//获取多个数据
public static SqlDataReader GetDataReader(string sql, params SqlParameter[] sps)
{
SqlConnection conn = new SqlConnection(constr);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
if (sps != null)
{
cmd.Parameters.AddRange(sps);
}
conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
//查询多条数据
public static DataTable GetDataTable(string sql, params SqlParameter[] sps)
{
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(sql, constr))
{
if (sps != null)
{
da.SelectCommand.Parameters.AddRange(sps);
}
da.Fill(dt);
}
return dt;
}
}