首页 > 代码库 > c# 连接数据库SqlHelper

c# 连接数据库SqlHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;


namespace 登录.DAL
{
public static class SqlHelper
{
private static readonly string conStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;

//执行增删改的
public static int ExecuteNonQuery(string sql, CommandType cmdType, params SqlParameter[] pms)
{
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteNonQuery();

}
}

}
//封装一个执行返回单个值的方法
public static object ExecuteScalar(string sql, CommandType cmdType, params SqlParameter[] pms)
{
using (SqlConnection con = new SqlConnection(conStr))
{

using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteScalar();

}
}

}
//返回sqlDataReader对象的方法
public static SqlDataReader ExecuteReader(string sql, CommandType cmdType, params SqlParameter[] pms)
{
SqlConnection con = new SqlConnection(conStr);
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);

}
try
{
con.Open();
return cmd.ExecuteReader();
}
catch (Exception)
{
con.Close();
con.Dispose();
throw;
}
}

}
//封装一个返回datatable的方法
public static DataTable ExecuteTable(string sql, CommandType cmdType, params SqlParameter[] pms)
{
DataTable dt = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conStr))
{
adapter.SelectCommand.CommandType = cmdType;
if(adapter !=null)
{
adapter.SelectCommand.Parameters.AddRange(pms);
}
adapter.Fill(dt);

}
return dt;

}
}

}

c# 连接数据库SqlHelper