SqlHelper For Sqlserver 一个简单实用的数据库访问帮助类

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace WebApp.DAL
{
public class SqlHelper
{
/// <summary>
///数据库的连接字符串
/// </summary>
private static readonly string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
/// <summary>
/// 查询数据库返回受影响的行 一般用于delete update insert
/// </summary>
/// <param name="sql">SQL语句</param>
/// <param name="type">查询的类型</param>
/// <param name="sp">结构化参数组</param>
/// <returns>int数值</returns>
public static int ExecuteNonQuery(string sql, CommandType type, params SqlParameter[] sp)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = new SqlConnection(constr);
cmd.CommandText = sql;
if (sp != null)
{
cmd.Parameters.AddRange(sp);
}
cmd.CommandType = type;
cmd.Connection.Open();
return cmd.ExecuteNonQuery();
}
}

/// <summary>
/// 查询数据库 返回一个dataReader
/// </summary>
/// <param name="sql">查询语句</param>
/// <param name="cmdType">查询的类型 比如sql语句查询,执行存储过程</param>
/// <param name="sp">结构化参数组</param>
/// <returns>dataReader</returns>
public static SqlDataReader ExeCuteReader(string sql, CommandType cmdType , params SqlParameter[] sp)
{

SqlConnection con = new System.Data.SqlClient.SqlConnection(constr);
using (SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
cmd.CommandText = sql;
cmd.CommandType = cmdType;
if (sp != null)
{
cmd.Parameters.AddRange(sp);
}
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
return cmd.ExecuteReader();
}
catch
{
con.Close();
cmd.Dispose();
throw;
}
}

}
/// <summary>
/// 查询数据库,返回查询结果的第一行第一列
/// </summary>
/// <param name="sql">查询语句</param>
/// <param name="cmdType">查询的类型</param>
/// <param name="sp">结构化查询的参数组</param>
/// <returns>Object对象</returns>
public static object ExecuteScalar(string sql, CommandType cmdType, params SqlParameter[] sp)
{
using (SqlConnection con=new System.Data.SqlClient.SqlConnection (constr))
{
using (SqlCommand cmd=new System.Data.SqlClient.SqlCommand (sql,con))
{
if (sp!=null)
{
cmd.Parameters.AddRange(sp);
}
con.Open();
return cmd.ExecuteScalar();
}
}
}
/// <summary>
/// 执行查询数据库 返回一个查询数据表
/// </summary>
/// <param name="sql">查询语句</param>
/// <param name="cmdType">查询的类型</param>
/// <param name="sp">结构化参数组</param>
/// <returns>datatable</returns>
public static DataTable ExecuteDataTable(string sql, CommandType cmdType , params SqlParameter[] sp)
{
DataTable dt = new System.Data.DataTable();
using (SqlDataAdapter sda=new System.Data.SqlClient.SqlDataAdapter (sql,constr))
{
sda.SelectCommand.CommandType = cmdType;
if (sp!=null)
{
sda.SelectCommand.Parameters.AddRange(sp);
}
sda.Fill(dt);
}
return dt;
}
}
}