class Sqlhelper
{
//数据库连接字符
private static string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
public static int ExecuteNonQutery(string sql, params SqlParameter[] parameters) //EXcuteNonQuery()方法是将返回数据执行相应的行数(int)
{
using (SqlConnection conn = new SqlConnection(connstr)) //程序与数据库创建连接(using{}主要用于对象实现类IDispose接口自动回收资源)
{
conn.Open(); //打开连接
using (SqlCommand cmd = conn.CreateCommand()) //创建数据操作命令语句
{
cmd.CommandText = sql; //创建Sql语句
cmd.Parameters.AddRange(parameters); //参数化,主要防止数据库注入漏洞
return cmd.ExecuteNonQuery();
}
}
}
public static object ExecuteScalar(string sql, params SqlParameter[] parameters) //EXecuteScalar()返回数据查询结果的第一行第一列数据对象(object)
{
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteScalar();
}
}
}
public static DataSet ExecuteDataSet(string sql, params SqlParameter[] parameters) // 数据小使用,把查询结果复制到本地(DataSet)内存中(离线)
{
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
SqlDataAdapter adapter = new SqlDataAdapter(cmd); //SqlDataAdaper主要是将执行结果填充到本地数据集中(Dataset)
DataSet dataset = new DataSet();
adapter.Fill(dataset);
return dataset;
}
}
}
}