实用的DBHelper帮助类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace BlogDAL
{
public class DBHelper
{
private static SqlConnection con;
private static SqlConnection Con {
get {
if (con == null)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
con.Open();
}
else if (con.State == ConnectionState.Broken)
{
con.Close();
con.Open();
}
else if (con.State == ConnectionState.Closed)
{
con.Open();
}
return con;
}
}
private static SqlCommand Cmd {
get {
return Con.CreateCommand();
}
}
public static bool Update(string sql) {
SqlCommand cmd = Cmd;
cmd.CommandText = sql;
return cmd. ExecuteNonQuery() > 0 ? true : false;
}
public static bool Update(string sql,SqlParameter[] pars)
{
SqlCommand cmd = Cmd;
cmd.CommandText = sql;
cmd.Parameters.AddRange(pars);
return cmd.ExecuteNonQuery() > 0 ? true : false;
}
public static bool Update(string sql, SqlParameter[] pars,out SqlConnection con)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddRange(pars);
return cmd.ExecuteNonQuery() > 0 ? true : false;
}
public static SqlDataReader SelectForDataReader(string sql)
{
SqlCommand cmd = Cmd;
cmd.CommandText = sql;
return cmd.ExecuteReader();
}
public static SqlDataReader SelectForDataReader(string sql,SqlParameter[] pars)
{
SqlCommand cmd = Cmd;
cmd.CommandText = sql;
cmd.Parameters.AddRange(pars);
return cmd.ExecuteReader();
}
public static SqlDataReader SelectForDataReader(string sql, SqlParameter[] pars,out SqlConnection con)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddRange(pars);
return cmd.ExecuteReader();
}
public static object SelectForScaler(string sql)
{
SqlCommand cmd = Cmd;
cmd.CommandText = sql;
return cmd.ExecuteScalar();
}
public static object SelectForScaler(string sql,SqlParameter[] pars)
{
SqlCommand cmd = Cmd;
cmd.Parameters.AddRange(pars);
cmd.CommandText = sql;
return cmd.ExecuteScalar();
}
}
}