using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using System.Security;
/// <summary>
///SqlHelper 是一个数据库的操作类
/// </summary>
public class SqlHelper
{
//这是一个数据库的所有访问
public SqlHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/*数据库字符串的连接字段的获取*/
public static string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
public static SqlConnection conn = getConn();
//初始化当前页的最后一条数据的编号和最前一条记录的编号
private static int lowerRecord = 0;
private static int upperRecord = 0;
/*获取数据库的连接sqlconnection对象conn*/
#region
/// <summary>
/// 获取数据库的连接对象
/// </summary>
/// <returns>返回一个sqlconnection对象conn</returns>
private static SqlConnection getConn()
{
conn = new SqlConnection(ConnectionString);
return conn;
}
#endregion
/// <summary>
/// 打开数据库连接
/// </summary>
private static void open()
{
if (conn.State == ConnectionState.Closed)
conn.Open();
}
/// <summary>
/// 关闭数据库连接
/// </summary>
private static void close()
{
if (conn.State == ConnectionState.Closed)
conn.Close();
}
/*销毁一个sqlconnection对象conn*/
#region
/// <summary>
/// 销毁conn对象
/// </summary>
///
private void Dispose()
{
try
{
conn.Close();
conn.Dispose();
}
catch { throw; }
}
#endregion
/*执行sql语句,返回受影响的行数*/
#region##执行sql语句,返回受影响的行数
/// <summary>
/// 返回strsql执行后影响的行数。
/// </summary>
/// <param name="strsql">存储过程的名字或者sql命令</param>
/// <param name="cmdParameter">sql语句的参数集合</param>
/// <returns></returns>
public static int ExecuteNonQuery(string strsql, params SqlParameter[] cmdParameter)
{
int effectNum = 0;
close();
open();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 60;
PrepareCommand(cmd, conn, null, strsql, cmdParameter);
effectNum = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return effectNum;
}
#endregion
/*执行sql语句,返回第一行第一列的数据*/
#region##执行sql语句,返回第一行第一列的数据
/// <summary>
/// 返回第一行第一列的对象:一般用来统计表的记录数
/// </summary>
/// <param name="strsql">要执行的sql语句,这种语句一般包含有:"select count(*) from table [where]"</param>
/// <param name="cmdParameter">执行的sql语句的参数</param>
/// <returns>返回第一行第一列的对象</returns>
public static object ExecuteScalar(string strsql,params SqlParameter[] cmdParameter)
{
try
{
close();
open();
object object1;
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, conn, null, strsql, cmdParameter);
object1 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return object1;
}
catch {
close();
throw;
}
}
#endregion
/*执行sql语句得到数据集sqlDataReader对象*/
#region##执行sql语句得到数据集sqlDataReader对象
/// <summary>
/// 获取执行完sql返回的数据结果集
/// </summary>
/// <param name="strsql">要执行的sql语句</param>
/// <param name="cmdParameter">sql语句的参数</param>
/// <returns>一个sqldatareader对象</returns>
public static SqlDataReader ExecuteReader(string strsql, params SqlParameter[] cmdParameter)
{
try
{
close();
open();
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, conn, null, strsql, cmdParameter);
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return sdr;
}
catch (Exception e)
{
close();
throw e;
}
}
#endregion
/*执行后返回一个数据集dataset*/
#region##执行后返回一个数据集dataset
/// <summary>
/// 执行后返回一个dataset结果数据集
/// </summary>
/// <param name="strsql">要执行的sql语句</param>
/// <param name="cmdParameter">要执行的sql语句的参数</param>
/// <returns>返回一个dataset结果数据集</returns>
public static DataSet ExecuteDataSet(string strsql, params SqlParameter[] cmdParameter)
{
close();
open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, getConn(), null, strsql, cmdParameter);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
try {
sda.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
catch (Exception e)
{
close();
throw e;
}
}
#endregion
/*准备要执行的sql语句*/
#region##准备要执行的sql语句
/// <summary>
/// 准备执行一个命令,拼接参数到cmd中。
/// </summary>
/// <param name="cmd">sql命令</param>
/// <param name="conn">Sql连接</param>
/// <param name="trans">Sql事务</param>
/// <param name="cmdText">命令文本,例如:Select * from Products</param>
/// <param name="cmdParms">执行命令的参数</param>
///
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
//判断连接的状态。如果是关闭状态,则打开
if (conn.State != ConnectionState.Open)
conn.Open();
//cmd属性赋值
cmd.Connection = conn;
cmd.CommandText = cmdText;
//是否需要用到事务处理
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;
//添加cmd需要的存储过程参数
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
#endregion
/*获得未阅主键集合*/
#region##获得未阅主键集合
/// <summary>
/// 分页使用:获得主键
/// </summary>
/// <param name="query">查询的sql语句</param>
/// <param name="passCount">已阅的记录数</param>
/// <returns>一个主键集合</returns>
private static string RecordID(string query, int passCount)
{
string strID = string.Empty;
close();
open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
if (passCount < 1)
{
strID += "," + "'"+sdr.GetString(0)+"'";
}
passCount--;
}
sdr.Close();
if (strID.Trim() != "")
return strID.Substring(1);
else
return "''";
}
#endregion
/*数据分页*/
#region##数据分页
/// <summary>
/// 数据分页
/// </summary>
/// <param name="pageIndex">当前页面index</param>
/// <param name="pageSize">页面大小</param>
/// <param name="strKey">主键</param>
/// <param name="showString">显示字段</param>
/// <param name="queryString">查询sql语句</param>
/// <param name="whereString">条件语句</param>
/// <param name="orderString">排序语句</param>
/// <returns></returns>
public static DataTable ExecutePager(int pageIndex,int pageSize, string strKey, string showString,string queryString,string whereString, string orderString)
{
close();
//open();
DataTable dt = new DataTable();
//判断分页的部分重要属性是否为空或者为非法数据,并纠正
if (pageIndex < 1) pageIndex = 1;
if (pageSize < 3) pageSize = 10;
if (showString.Equals(string.Empty)) showString = "*";
if (orderString.Equals(string.Empty)) orderString = strKey + "asc";
if (whereString.Equals(string.Empty)) whereString = "1=1";
////获得数据库连接对象并打开数据库为以后做准备
//if (conn.State == ConnectionState.Closed)
//{
// conn.Open();
//}
//获取数据表
string table = string.Format("{0} tempVw",queryString);
int recordCount = dataCount(table);
//定义一个sqlcommand对象
SqlCommand cmdRecord;
//判断总记录数是否小于页面的显示记录数
if (recordCount <= pageSize){
cmdRecord = new SqlCommand(string.Format("select top {0} {1} from {2} {3}",recordCount,showString,table,whereString),conn);
}
else {
//计算当前页的最前和最后一条记录编号
lowerRecord = pageIndex * pageSize;
upperRecord = lowerRecord - pageSize;
//获取还未阅览的主键
string recordIDs = RecordID(string.Format("select top {0} {1} from {2} {3}",lowerRecord, strKey, table,whereString), upperRecord);
string STR = string.Format("select {0} from {1} where {2} in ({3}) order by {4}", showString, table, strKey, recordIDs, orderString);
cmdRecord = new SqlCommand(string.Format("select {0} from {1} where {2} in ({3}) order by {4}", showString, table,strKey,recordIDs, orderString), conn);
}
SqlDataAdapter sda = new SqlDataAdapter(cmdRecord);
sda.Fill(dt);
return dt;
}
#endregion
/*计算总记录数*/
#region##计算总记录数
/// <summary>
/// 计算总的记录数
/// </summary>
/// <param name="table">要查询的表,或者是要查询的语句</param>
/// <returns>总的记录条数</returns>
public static int dataCount(string table)
{
close();
open();
SqlCommand cmdCount = new SqlCommand(string.Format("select count(*) from {0}", table), conn);
//获得总记录数
int recordCount = Convert.ToInt32(cmdCount.ExecuteScalar());
close();
return recordCount;
}
#endregion
/*计算总页数*/
#region##计算总页数
/// <summary>
/// 计算总页数
/// </summary>
/// <param name="queryString">查询sql语句</param>
/// <param name="pageSize">页面大小</param>
/// <returns>总页数</returns>
public static int pageCount(string queryString, int pageSize)
{
string table = string.Format("({0}) tempVw", queryString);
int recordCount = dataCount(table);
int pageCount;
if (recordCount % pageSize == 0)
pageCount = recordCount / pageSize;
else
pageCount = recordCount / pageSize + 1;
return pageCount;
}
#endregion
}