<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace DAL
{
public class SQLHelper
{
private SqlConnection conn = null;
private SqlCommand cmd = null;
private SqlDataReader sdr = null;
public SQLHelper()
{
string connStr = ConfigurationManager.AppSettings["connStr"];
conn = new SqlConnection(connStr);
}
private SqlConnection GetConn()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
return conn;
}
/// <summary>
/// 该方法执行不带参数的SQL增删改语句或存储过程
/// </summary>
/// <param name="cmdText">SQL增删改语句或存储过程</param>
/// <param name="ct">命令类型</param>
/// <returns></returns>
public int ExecuteNonQuery(string cmdText, CommandType ct)
{
int res;
try
{
cmd = new SqlCommand(cmdText, GetConn());
cmd.CommandType = ct;
res = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
//conn.Close();
return res;
}
/// <summary>
/// 该方法执行带参数的SQL增删改语句或存储过程
/// </summary>
/// <param name="cmdText">SQL增删改语句或存储过程</param>
/// <param name="ct">命令类型</param>
/// <param name="paras">参数集合</param>
/// <returns></returns>
public int ExecuteNonQuery(string cmdText, CommandType ct, SqlParameter[] paras)
{
int res;
using (cmd = new SqlCommand(cmdText, GetConn()))
{
cmd.CommandType = ct;
cmd.Parameters.AddRange(paras);
res = cmd.ExecuteNonQuery();
}
return res;
}
/// <summary>
/// 该方法执行不带参数的SQL查询语句或存储过程
/// </summary>
/// <param name="cmdText">SQL查询语句或存储过程</param>
/// <param name="ct">命令类型</param>
/// <returns></returns>
public DataTable ExecuteQuery(string cmdText, CommandType ct)
{
DataTable dt = new DataTable();
cmd = new SqlCommand(cmdText, GetConn());
cmd.CommandType = ct;
using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) //用Using对Connection进行释放
{
dt.Load(sdr);//接收IDataReader
}
//sdr.Close();
//conn.Close();
return dt;
}
/// <summary>
/// 执行带参数的SQL查询语句或存储过程
/// </summary>
/// <param name="cmdText">SQL查询语句或存储过程</param>
/// <param name="ct">命令类型</param>
/// <param name="paras">参数集合</param>
/// <returns></returns>
public DataTable ExecuteQuery(string cmdText, CommandType ct, SqlParameter[] paras)
{
DataTable dt = new DataTable();
cmd = new SqlCommand(cmdText, GetConn());
cmd.CommandType = ct;
cmd.Parameters.AddRange(paras);
using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) //用Using对Connection进行释放
{
dt.Load(sdr);//接收IDataReader
}
return dt;
}
}
}
</span>
C#编写SQLHelper
最新推荐文章于 2023-04-21 11:06:34 发布