using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RuPengWang.DAL
{
public class SqlHelper
{
private static readonly string constr = ConfigurationManager.AppSettings["constr"];
/// <summary>
/// 數據表的增、刪、改;
/// </summary>
/// <param name="conn"></param>
/// <param name="sql"></param>
/// <param name="sp"></param>
/// <returns></returns>
public static int ExecuteNonQuery(string sql, params SqlParameter[] sp)
{
using (SqlConnection con = new SqlConnection(SqlHelper.constr))
{
return SqlHelper.ExecuteNonQuery(con, sql, sp);
}
}
public static int ExecuteNonQuery(SqlConnection conn, string sql, params SqlParameter[] ps)
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddRange(ps);
return cmd.ExecuteNonQuery();
}
}
/// <summary>
/// 執行一條返回第一條記錄第一列的SqlCommand命令,通過專用的連接字符串。
/// 使用參數數組提供參數
/// </summary>
/// <param name="conn"></param>
/// <param name="sql"></param>
/// <param name="ps"></param>
/// <returns>返回一個object數據</returns>
public static object ExecuteScale(SqlConnection conn,string sql, params SqlParameter[] ps)
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddRange(ps);
return cmd.ExecuteScalar();
}
}
/// <summary>
/// 執行一條返回第一條記錄第一列的SqlCommand命令,通過專用的連接字符串。
/// 使用參數數組提供參數
/// </summary>
/// <param name="sql">sql語句</param>
/// <param name="ps">參數</param>
/// <returns>返回一個object數據</returns>
public static object ExecuteScale(string sql, params SqlParameter[] ps)
{
using (SqlConnection conn = new SqlConnection(SqlHelper.constr))
{
return SqlHelper.ExecuteScale(conn, sql, ps);
}
}
/// <summary>
/// 該方法用於讀取數據
/// </summary>
/// <param name="sql">sql語句</param>
/// <param name="sp">sql參數</param>
/// <returns>SqlDataReader類型</returns>
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] sp)
{
SqlConnection conn = new SqlConnection(constr);
using(SqlCommand cmd=new SqlCommand(sql,conn))
{
cmd.Parameters.AddRange(sp);
try{
conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch(Exception ex){
conn.Close();
conn.Dispose();
throw ex;
}
}
}
/// <summary>
/// 讀取數據返回的是datatable
/// </summary>
/// <param name="sql"></param>
/// <param name="ps"></param>
/// <returns>DataTable</returns>
public static DataTable ExecuteTable(string sql, params SqlParameter[] ps)
{
DataTable dt=new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(sql, constr))
{
if (ps != null)
{
da.SelectCommand.Parameters.AddRange(ps);
}
da.Fill(dt);
}
return dt;
}
}
}