using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Data.Common; namespace SWDataDB.DAL
{
public class SQLHelper
{
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance,
/// scalable best practices for common uses of SqlClient.
/// </summary> //Database connection strings
public static readonly string SQLConnString = ConfigurationManager.ConnectionStrings["SQLConnString"].ConnectionString;
//public static readonly string SQLBookConnString = ConfigurationManager.ConnectionStrings["SQLBookConnString"].ConnectionString;
// Hashtable to store cached parameters
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); /// <summary>
/// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{ SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
cmd.CommandTimeout = 999;
int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear();
return val;
}
} public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
ad.Fill(data);
cmd.Parameters.Clear();
return data;
}
} /// <summary>
/// Execute a SqlCommand (that returns no resultset) against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{ SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
cmd.CommandTimeout = 999;
int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear();
return val;
} /// <summary>
/// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="trans">an existing sql transaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
cmd.CommandTimeout = 999;
int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 获得datatable
/// </summary>
/// <param name="connectionString"></param>
/// <param name="cmdType"></param>
/// <param name="cmdText"></param>
/// <param name="commandParameters"></param>
/// <returns></returns>
public static DataTable ExecuteReaderDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
DataSet dataset = new DataSet();
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, conn); adapter.Fill(dataset);
cmd.CommandTimeout = 999;
cmd.Parameters.Clear();
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
} return dataset.Tables[0];
}
/// <summary>
/// Execute a SqlCommand that returns a resultset against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the results</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString); // we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
cmd.CommandTimeout = 999;
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
} /// <summary>
/// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand(); using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
cmd.CommandTimeout = 999;
object val = cmd.ExecuteScalar(); cmd.Parameters.Clear();
return val;
}
} /// <summary>
/// Execute a SqlCommand that returns the first column of the first record against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{ SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
cmd.CommandTimeout = 999;
object val = cmd.ExecuteScalar(); cmd.Parameters.Clear();
return val;
} /// <summary>
/// add parameter array to the cache
/// </summary>
/// <param name="cacheKey">Key to the parameter cache</param>
/// <param name="cmdParms">an array of SqlParamters to be cached</param>
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
} /// <summary>
/// Retrieve cached parameters
/// </summary>
/// <param name="cacheKey">key used to lookup parameters</param>
/// <returns>Cached SqlParamters array</returns>
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; if (cachedParms == null)
return null; SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length]; for (int i = 0, j = cachedParms.Length; i < j; i++)
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms;
} /// <summary>
/// Prepare a command for execution
/// </summary>
/// <param name="cmd">SqlCommand object</param>
/// <param name="conn">SqlConnection object</param>
/// <param name="trans">SqlTransaction object</param>
/// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
/// <param name="cmdText">Command text, e.g. Select * from Products</param>
/// <param name="cmdParms">SqlParameters to use in the command</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{ if (conn.State != ConnectionState.Open)
conn.Open(); cmd.Connection = conn;
cmd.CommandText = cmdText; if (trans != null)
cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
} /// <summary>
/// 单表(视图)获取分页SQL语句
/// </summary>
/// <param name="tableName">表名或视图名</param>
/// <param name="key">唯一键</param>
/// <param name="fields">获取的字段</param>
/// <param name="condition">查询条件(不包含WHERE)</param>
/// <param name="collatingSequence">排序规则(不包含ORDER BY)</param>
/// <param name="pageSize">页大小</param>
/// <param name="pageIndex">页码(从1开始)</param>
/// <returns>分页SQL语句</returns>
public static string GetPagingSQL(
string tableName,
string key,
string fields,
string condition,
string collatingSequence,
long pageSize,
long pageIndex)
{
string whereClause = string.Empty;
if (!string.IsNullOrEmpty(condition))
{
whereClause = string.Format("WHERE {0}", condition);
} if (string.IsNullOrEmpty(collatingSequence))
{
collatingSequence = string.Format("{0} ASC", key);
} StringBuilder sbSql = new StringBuilder(); sbSql.AppendFormat("SELECT {0} ", PrependTableName(tableName, fields, ','));
sbSql.AppendFormat("FROM ( SELECT TOP {0} ", pageSize * pageIndex);
sbSql.AppendFormat(" [_RowNum_] = ROW_NUMBER() OVER ( ORDER BY {0} ), ", collatingSequence);
sbSql.AppendFormat(" {0} ", key);
sbSql.AppendFormat(" FROM {0} ", tableName);
sbSql.AppendFormat(" {0} ", whereClause);
sbSql.AppendFormat(" ) AS [_TempTable_] ");
sbSql.AppendFormat(" INNER JOIN {0} ON [_TempTable_].{1} = {0}.{1} ", tableName, key);
sbSql.AppendFormat("WHERE [_TempTable_].[_RowNum_] > {0} ", pageSize * (pageIndex - 1));
sbSql.AppendFormat("ORDER BY [_TempTable_].[_RowNum_] ASC "); return sbSql.ToString();
} /// <summary>
/// 给字段添加表名前缀
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="fields">字段</param>
/// <param name="separator">标识字段间的分隔符</param>
/// <returns></returns>
public static string PrependTableName(string tableName, string fields, char separator)
{
StringBuilder sbFields = new StringBuilder(); string[] fieldArr = fields.Trim(separator).Split(separator);
foreach (string str in fieldArr)
{
sbFields.AppendFormat("{0}.{1}{2}", tableName, str.Trim(), separator);
} return sbFields.ToString().TrimEnd(separator);
} /*
nzperfect [no_mIss] 高效通用分页存储过程(双向检索) 2007.5.7 QQ:34813284
敬告:适用于单一主键或存在唯一值列的表或视图
ps:Sql语句为8000字节,调用时请注意传入参数及sql总长度不要超过指定范围
* @TableName VARCHAR(200), --表名
@FieldList VARCHAR(2000), --显示列名,如果是全部字段则为*
@PrimaryKey VARCHAR(100), --单一主键或唯一值键
@Where VARCHAR(2000), --查询条件 不含'where'字符,如id>10 and len(userid)>9
@Order VARCHAR(1000), --排序 不含'order by'字符,如id asc,userid desc,必须指定asc或desc
--注意当@SortType=3时生效,记住一定要在最后加上主键,否则会让你比较郁闷
@SortType INT, --排序规则 1:正序asc 2:倒序desc 3:多列排序方法
@RecorderCount INT, --记录总数 0:会返回总记录
@PageSize INT, --每页输出的记录数
@PageIndex INT, --当前页数
@TotalCount INT OUTPUT, --记返回总记录
@TotalPageCount INT OUTPUT --返回总页数
*/
/// <summary>
/// 调用存储过程 分页查询
/// </summary>
/// <param name="TableName">表名</param>
/// <param name="FieldList">显示列名,如果是全部字段则为*</param>
/// <param name="PrimaryKey">单一主键或唯一值键</param>
/// <param name="Where">查询条件 不含'where'字符,如id>10 and len(userid)>9</param>
/// <param name="Order">排序 不含'order by'字符,如id asc,userid desc,必须指定asc或desc</param>
/// <param name="SortType">排序规则</param>
/// <param name="RecorderCount">记录总数</param>
/// <param name="PageSize">每页输出的记录数</param>
/// <param name="PageIndex">当前页数</param>
/// <param name="TotalCount">记返回总记录</param>
/// <param name="TotalPageCount">返回总页数</param>
/// <returns></returns>
public static DataSet P_viewPage(string TableName, string FieldList, string PrimaryKey, string Where, string Order,
int SortType, int RecorderCount, int PageSize, int PageIndex, out int TotalCount, out int TotalPageCount)
{
string strSql = "P_viewPage";
int totalCount = 0;
int totalPageCount = 0; SqlParameter[] arrSqlPara = new SqlParameter[]
{ new SqlParameter("@TableName",TableName),
new SqlParameter("@FieldList",FieldList),
new SqlParameter("@PrimaryKey",PrimaryKey),
new SqlParameter("@Where",Where),
new SqlParameter("@Order",Order),
new SqlParameter("@SortType",SortType),
new SqlParameter("@RecorderCount",RecorderCount),
new SqlParameter("@PageSize",PageSize),
new SqlParameter("@PageIndex",PageIndex),
new SqlParameter("@TotalCount",totalCount),
new SqlParameter("@TotalPageCount",totalPageCount), }; arrSqlPara[9].Direction = ParameterDirection.Output;
arrSqlPara[10].Direction = ParameterDirection.Output; DataSet ds = SQLHelper.ExecuteDataSet(SQLHelper.SQLConnString, CommandType.StoredProcedure, strSql, arrSqlPara); TotalCount = int.Parse(arrSqlPara[9].Value.ToString());
TotalPageCount = int.Parse(arrSqlPara[10].Value.ToString()); return ds; //return SQLHelper.ExecuteNonQuery(SQLHelper.SQLConnString, CommandType.StoredProcedure, strSql, arrSqlPara);
} }
}

SQL Server数据库连接类SQLHelper.cs的更多相关文章

  1. SQL Server数据库连接,Web.config的正确配置 [转]

    http://database.51cto.com/art/201007/213289.htm 此文章主要介绍的是Web.config正确配置SQL Server数据库连接的实际擦步骤,在图5-6中, ...

  2. SQL server 数据库连接方式分析

    SQL server 数据库连接方式图示: ODBC和OLEDB连接的区别 ODBC(开放数据库互连):是Microsoft引进的一种早期数据库接口技术.它实际上是ADO的前身.早期的数据库连接是非常 ...

  3. MS SQL Server 数据库连接字符串详解

    MS SQL Server 数据库连接字符串详解 原地址:http://blog.csdn.net/jhhja/article/details/6096565 问题 : 超时时间已到.在从池中获取连接 ...

  4. 如何获取SQL Server数据库连接字符串的某些部分

    有的时候需要获取SQL Server数据库连接字符串的某些部分.用正则表达式可能有点麻烦. 其实有一个比较简单的方法--使用SqlConnectionStringBuilder. var builde ...

  5. SQL Server数据库连接字符串的组成

    DB驱动程序常见的驱动程序如下: ODBC   ODBC(Open Database Connectivity,开放数据库互连)是微软公司开放服务结构(WOSA,Windows Open Servic ...

  6. ADO.NET中SQL Server数据库连接池

    连接到数据库服务器通常由几个需要很长时间的步骤组成. 必须建立物理通道(例如套接字或命名管道),必须与服务器进行初次握手,必须分析连接字符串信息,必须由服务器对连接进行身份验证,必须运行检查以便在当前 ...

  7. sql server数据库连接问题处理

    下面请一字一句地看,一遍就设置成功,比你设置几十遍失败,费时会少得多. 首先,在连接数据库之前必须保证SQL Server 2012是采用SQL Server身份验证方式而不是windows身份验证方 ...

  8. [转]MS SQL Server 数据库连接字符串详解

    http://blog.csdn.net/jackiehome/article/details/8668121 问题 : 超时时间已到.在从池中获取连接之前超时时间已过.出现这种情况可能是因为所有池连 ...

  9. (C# SQL Server) 数据库连接字符串

    Debug 一个SQL Server 2008 数据库连接的问题,老是提示: [67944] System.Data.SqlClient.SqlException (0x80131904): 在与 S ...

随机推荐

  1. How to Display Image In Picturebox in VC++ from Iplimage and Mat

    Introduction This tip/trick will be useful to OpenCV programmers, who wish to use Windows Form appli ...

  2. 高级I/O之异步I/O

    A synchronous I/O operation causes the requesting process to be blocked until that I/O operation com ...

  3. 关于Android M RuntimePermission的问题

    关于shouldShowRequestPermissionRationale的理解, 在onRequestPermissionsResult里如果用户拒绝了权限, 可以调用这个api, 返回true, ...

  4. MySQL_update同一张表

    update tb1 inner join(select type, count(*) as cntfrom tb1 group by type)as der using(type)set tb1.c ...

  5. 如何制作按钮hover状态

    1.选中文字加背景图层 2.Ctrl+J复制图层,向下轻移. 3.点击所复制图层的背景图层,右键选中——混合选项 弹出图层样式框: 4.选择渐变叠加,将渐变——反向勾选上,确定: 5.完成,效果如图.

  6. document.body.clientHeight与document.documentElement.clientHeight

    当你的网页有: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www ...

  7. 纯C++ 连接SQL Server2005 数据库读写操作的小例子

    一个测试c++链接 sql server 数据库的例子// 数据库说明// 数据库用户为 sa , 密码为 空// 数据库为 MyDB// 表为 UserInfo// 表字段为 Name . Pass ...

  8. mysql单引号和双引号的用法

    表名,列名最好用`(esc下面那个,不用`会出错) 这就要从双引号和单引号的作用讲起:双引号里面的字段会经过编译器解释然后再当作HTML代码输出,但是单引号里面的不需要解释,直接输出.例如:$abc= ...

  9. 给jdk写注释系列之jdk1.6容器(12)-PriorityQueue源码解析

    PriorityQueue是一种什么样的容器呢?看过前面的几个jdk容器分析的话,看到Queue这个单词你一定会,哦~这是一种队列.是的,PriorityQueue是一种队列,但是它又是一种什么样的队 ...

  10. LeetCode 258

    Add Digits Given a non-negative integer num, repeatedly add all its digits until the result has only ...