SqlHelper 类
// 一个自用的 SqlHelper 类 利用了刚学习到的 扩展方法 http://technet.microsoft.com/zh-cn/bb383977
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance,
/// scalable best practices for common uses of SqlClient.
/// </summary>
public abstract class SqlHelper
{
//Database connection strings
public static readonly string connStr = ConfigurationManager.ConnectionStrings["SQLConnString"].ConnectionString; public static int ExecuteNonQuery(string cmdText, params SqlParameter[] cmdParameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
//if (conn.State != ConnectionState.Open) conn.Open();
conn.QuickOpen();
cmd.Parameters.Clear();
foreach (SqlParameter item in cmdParameters)
{
cmd.Parameters.Add(item);
}
return cmd.ExecuteNonQuery();
}
}
} /// <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);
int val = cmd.ExecuteNonQuery();
return val;
} /// <summary>
/// 执行一个查询,返回一个object
/// </summary>
/// <param name="cmdText">查询文本</param>
/// <returns>结果</returns>
public static object ExecuteScalar(string cmdText, params SqlParameter[] cmdParameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
//if (conn.State != ConnectionState.Open) conn.Open();
conn.QuickOpen();
cmd.Parameters.Clear();
foreach (SqlParameter item in cmdParameters)
{
cmd.Parameters.Add(item);
} return cmd.ExecuteScalar();
}
}
} /// <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 object ExecuteScalar(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
return cmd.ExecuteScalar();
} /// <summary>
/// 执行一个查询,返回一个结果集
/// </summary>
/// <param name="cmdText">查询文本</param>
/// <returns>结果集</returns>
public static DataTable DB_Select(string cmdText, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = BuildQueryCommand(conn, cmdText, CommandType.Text, parameters);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
} /// <summary>
/// 执行一个查询,返回一个结果集
/// </summary>
/// <param name="cmdText">查询文本</param>
/// <returns>结果集</returns>
public static DataTable DB_Select(string cmdText, CommandType type, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = BuildQueryCommand(conn, cmdText, type, parameters);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
} /// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static DataTable RunProcedure(string storedProcName, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.QuickOpen();
DataTable dt = new DataTable();
//conn.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(conn, storedProcName, parameters);
sqlDA.Fill(dt);
return dt;
}
} /// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static DataSet RunProcedure(string storedProcName, string tableName, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.QuickOpen();
DataSet dataSet = new DataSet();
//conn.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(conn, storedProcName, parameters);
sqlDA.Fill(dataSet, tableName);
conn.Close();
return dataSet;
}
} /// <summary>
/// 构建 SqlCommand 对象
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, params SqlParameter[] parameters)
{
return BuildQueryCommand(connection, storedProcName, CommandType.StoredProcedure, parameters);
} /// <summary>
/// 构建 SqlCommand 对象
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static SqlCommand BuildQueryCommand(SqlConnection connection, string cmdText, CommandType type, params SqlParameter[] parameters)
{
SqlCommand command = new SqlCommand(cmdText, connection);
command.CommandType = type;
foreach (SqlParameter parameter in parameters)
{
if (parameter != null)
{
// 检查未分配值的输出参数,将其分配以DBNull.Value.
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
command.Parameters.Add(parameter);
}
} return command;
} /// <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();
conn.QuickOpen();
cmd.Connection = conn;
cmd.CommandText = cmdText; if (trans != null)
cmd.Transaction = trans; cmd.CommandType = cmdType;
cmd.Parameters.Clear();
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if (parameter != null)
{
// 检查未分配值的输出参数,将其分配以DBNull.Value.
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
} }
} public static class SqlExtensions
{
public static void QuickOpen(this SqlConnection conn)
{
int timeout = Generic.ToInt32(ConfigurationManager.AppSettings["TimeOut"]);
timeout = Math.Max(Math.Min(, timeout), ); // We'll use a Stopwatch here for simplicity. A comparison to a stored DateTime.Now value could also be used
Stopwatch sw = new Stopwatch();
bool connectSuccess = false; // Try to open the connection, if anything goes wrong, make sure we set connectSuccess = false
Thread t = new Thread(delegate()
{
try
{
sw.Start();
conn.Open();
connectSuccess = true;
}
catch { }
}); // Make sure it's marked as a background thread so it'll get cleaned up automatically
t.IsBackground = true;
t.Start(); // Keep trying to join the thread until we either succeed or the timeout value has been exceeded
while (timeout > sw.ElapsedMilliseconds)
if (t.Join())
break; // If we didn't connect successfully, throw an exception
if (!connectSuccess)
throw new Exception("连接超时!\r\n未能连接到数据库!\r\n如有需要,可更改App.config 中的 TimeOut 值");
}
}
SqlHelper 类的更多相关文章
- 最新的SqlHelper 类
最新的SqlHelper 类 摘自:http://www.cnblogs.com/sufei/archive/2010/01/14/1648026.html using System; using S ...
- c#中sqlhelper类的编写(二)
上一篇文章讲了简易版的SqlHelper类的编写,我们在这里就上一篇文章末尾提出的问题写出解决方案. sql语句注入攻击已经是众所周知的了.我们如何在C#中保护自己的数据库不被这样的方式攻击呢? 不用 ...
- JAVA WEB SQLHelper类的封装
在这次做项目中,我对自己最满意的就是封装了一下SQLHelper类,我对自己感到骄傲主要是 我是初学者,我刚开始不知道可以这样做,我只是想着试着去这样做了,结果真的可以,所以我 在我的模块就自己封装了 ...
- c#中sqlhelper类的编写(一)
在.net平台的项目开发中,凡是用到数据库交互的,都有必要了解SqlHelper类的原理. 步骤一: 我就拿WPF项目开发作为例子.首先要新建一个App.config(应用程序配置文件).注意,在VS ...
- [置顶] 自己写sqlhelper类
自己写sqlhelper类 using System; using System.Collections.Generic; using System.Configuration; using Syst ...
- ADO.NET复习——自己编写SqlHelper类
今天复习了一次ADO.NET基础,整理一下自己的认为的重点: 编写SqlHelper类,方便我们执行数据库语句,这时可以直接调用封装在SqlHelper类的方法.现在大多数公司面试的时候,给你的面试题 ...
- 【转载】微软官方提供的Sqlserver数据库操作帮助类SQLHelper类
在.NET平台中,C#语言一般使用ADO.NET组件来操作Sqlserver数据库,通过ADO.NET组件可以实现连接数据库.查询数据集.执行SQL语句以及关闭数据库连接等操作,为此网上有很多开发者自 ...
- 微软官方SqlHelper类 数据库辅助操作类
数据库操作类真的没有必要自己去写,因为成熟的类库真的非常完善了,拿来直接用就好,省时省力. 本文就为大家介绍微软官方的程序PetShop4.0中的SqlHelper类,先来做一下简单的介绍,PetSh ...
- 整理出一个比较实用的SqlHelper类 满足大多数情况的使用
/// <summary> /// SqlHelper类 by zy 2016-3-11 /// </summary> public sealed class SqlHelpe ...
- C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法
本文实例讲述了C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法.分享给大家供大家参考.具体如下: 这个类不是我实现的,英文原文地址为http://www.egg ...
随机推荐
- ffmpeg处理视频命令
一:视频添加图片水印 ffmpeg -i a.mp4 -vf "movie=a.jpg[watermark];[in][watermark] overlay=main_w-overlay_w ...
- smbfs
Hi I tried to mount a network share (smbfs) but it complains about the lack of kernel support. To so ...
- deep_learning_Function_reduction_indices的用法
在tf.reduce_sum等函数中,有一个reduction_indices参数,表示函数的处理维度. 当没有reduction_indices这个参数,此时该参数取默认值None,将把input_ ...
- K8S搭建过程随笔_证书CFSSL
安装CFSSL mkdir -p /opt/k8s/cert && cd /opt/k8swget https://pkg.cfssl.org/R1.2/cfssl_linux-amd ...
- Redis08-击穿&穿透&雪崩&spring data redis
一.常见概念 击穿: 概念:redis作为缓存,设置了key的过期时间,key在过期的时候刚好出现并发访问,直接击穿redis,访问数据库 解决方案:使用setnx() ->相当于一把锁,设置的 ...
- windows 环境下基于Python 的GDAL 安装
最近由于需要利用pytho处理地理空间数据,但是python本身并没有访问和处理地理空间数据的包,只能借助于GDAL(Geospatial Data Abstraction Library)来进行访问 ...
- QT对话框
QFileDialog:文件对话框 QString fileName=QFileDialog::getOpenFileName(this,"打开文件", "/" ...
- spring cache会默认使用redis作为缓存吗?
web项目中,只需要配置 redis 的IP,端口,用户名和密码就可以使用redis作为缓存了,不需要在在java 代码中配置redisConfig,redisConfig只是作为缓存配置的辅助,比如 ...
- Java程序中使用 Jsoup 爬虫( 简单示例 )
一.maven项目里pom添加jsoup依赖 <dependency> <groupId>org.jsoup</groupId> <artifactId> ...
- Servlet中的乱码问题及解决办法
假设现在有个form表单,当页面中提交一个包含中文的请求时,在服务端有可能出现中文乱码问题. <!DOCTYPE html> <html> <head> <m ...