public static class SqlHelper
{
//通过配置文件获取连接字符创
private static readonly string constr = ConfigurationManager.ConnectionStrings["str"].ConnectionString;
/// <summary>
/// 执行增,删,改的方法
/// </summary>
/// <param name="sql">要执行的sql语句</param>
/// <param name="spt">参数化查询的参数</param>
/// <returns>影响的行数</returns>
public static int ExecuteNonquery(string sql, params SqlParameter[] spt)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
if (spt != null)
{
cmd.Parameters.AddRange(spt);
}
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 执行返回一行一列数据的方法
/// </summary>
/// <param name="sql"></param>
/// <param name="spt"></param>
/// <returns></returns>
public static object ExecuteScalar(string sql, params SqlParameter[] spt)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
if (spt != null)
{
cmd.Parameters.AddRange(spt);
}
return cmd.ExecuteScalar();
}
}
}
/// <summary>
/// 执行查询语句的方法
/// </summary>
/// <param name="sql"></param>
/// <param name="spt"></param>
/// <returns>SqlDataReader类型</returns>
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] spt)
{
SqlConnection con = new SqlConnection(constr);
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (spt != null)
{
cmd.Parameters.AddRange(spt);
} try
{
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception)
{
con.Close();
con.Dispose();
throw;
}
}
}
/// <summary>
/// 用到DataAdapter的方法,
/// </summary>
/// <param name="sql"></param>
/// <param name="spt"></param>
/// <returns>DataTable类型</returns>
public static DataTable ExecuteAdapter(string sql, params SqlParameter[] spt)
{
DataTable ds = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(sql, constr))
{
if (spt != null)
{
da.SelectCommand.Parameters.AddRange(spt);
}
da.Fill(ds);
}
return ds; }
}