|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LoiginSystem
{
public static class SqlHelper
{
//定义一个只读的内部数据库连接字符串
private static readonly string conStr = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;
//1.执行增、删、改
public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
{
using(SqlConnection con = new SqlConnection(conStr))
{
using(SqlCommand cmd= new SqlCommand(sql, con))
{
if( pms != null )
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
//2.执行查询返回单个值
public static object ExecuteScalar(string sql, params SqlParameter[] pms)
{
using(SqlConnection con = new SqlConnection(conStr))
{
using(SqlCommand cmd= new SqlCommand(sql, con))
{
if( pms != null )
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteScalar();
}
}
}
//3.执行查询返回多个值
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
{
SqlConnection conn = new SqlConnection(conStr);
using(SqlCommand cmd=new SqlCommand(sql, conn))
{
if( pms != null)
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(pms);
}
try
{
conn.Open();
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}catch(Exception ex)
{
conn.Close();
conn.Dispose();
throw ex;
}
}
}
}
}
|
|