DBHerperl类
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Collections;
using System.Transactions; namespace Boss.DAL
{
/// <summary>
/// 数据库的通用访问类
/// 此类为抽象类,不允许实例化,在应用时直接调用
/// </summary>
public abstract class SqlHelperEx
{
#region 数据操作 /// <summary>
/// 打开数据库链接
/// </summary>
/// <param name="conn"></param>
/// <returns></returns>
public static SqlConnection ConnOpen(string conn)
{
try
{
SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings[conn].ConnectionString);
myConn.Open();
return myConn;
}
catch (SqlException ex)
{
throw ex;
}
} /// <summary>
/// 关闭数据库链接
/// </summary>
/// <param name="myConn">数据库连接对象SqlConnection</param>
public static void ConnClose(SqlConnection myConn)
{
try
{ if (myConn.State == ConnectionState.Open)
{
myConn.Close();
myConn.Dispose();
}
}
catch (SqlException ex)
{
throw ex;
}
} /// <summary>
/// 获取SqlDataReader 带参
/// </summary>
/// <param name="strSql">Sql语句</param>
/// <param name="myConn">SqlConnection</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSql, SqlConnection myConn, params SqlParameter[] cmdParms)
{
try
{
SqlDataReader myDr;
SqlCommand myComm = GetSqlCommand(strSql, myConn, cmdParms);
myDr = myComm.ExecuteReader();
myComm.Dispose();
return myDr;
}
catch (SqlException ex)
{
throw ex;
}
} /// <summary>
/// 获取SqlDataReader 无参
/// </summary>
/// <param name="strSql">Sql语句</param>
/// <param name="myConn">SqlConnection</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSql, SqlConnection myConn)
{
try
{
SqlDataReader myDr;
SqlCommand myComm = GetSqlCommand(strSql, myConn, null);
myDr = myComm.ExecuteReader();
myComm.Dispose();
return myDr;
}
catch (SqlException ex)
{
throw ex;
}
} /// <summary>
/// 执行sql语句(有参数)
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="cmdParms">参数</param>
/// <returns>返回影响行数</returns>
public static int ExecuteNonQuery(string strSql, SqlConnection myConn, params SqlParameter[] cmdParms)
{
int Result = -;
try
{
SqlCommand myComm = GetSqlCommand(strSql, myConn, cmdParms);
Result = myComm.ExecuteNonQuery();
myComm.Dispose();
WriteLog(strSql, cmdParms);
}
catch (SqlException ex)
{
throw ex;
}
return Result;
}
/// <summary>
/// 执行sql语句(无参数)
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="cmdParms">参数</param>
/// <returns>返回影响行数</returns>
public static int ExecuteNonQuery(string strSql, SqlConnection myConn)
{
int Result = -;
try
{
SqlCommand myComm = GetSqlCommand(strSql, myConn, null);
Result = myComm.ExecuteNonQuery();
myComm.Dispose();
WriteLog(strSql);
}
catch (SqlException ex)
{
throw ex;
}
return Result;
} public static int ExecuteNonQueryLog(string strSql, SqlConnection myConn, params SqlParameter[] cmdParms)
{
int Result = -;
try
{
SqlCommand myComm = GetSqlCommand(strSql, myConn, cmdParms);
Result = myComm.ExecuteNonQuery();
myComm.Dispose();
}
catch (SqlException ex)
{
throw ex;
}
return Result;
} /// <summary>
/// 获取DataSet 带参
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="myConn">数据库连接</param>
/// <returns>DataSet</returns>
public static DataSet GetDataSet(string strSql, SqlConnection myConn, params SqlParameter[] cmdParms)
{ try
{
DataSet ds = new DataSet();
SqlCommand sqlCommand = GetSqlCommand(strSql, myConn, cmdParms);
SqlDataAdapter adpt = new SqlDataAdapter(sqlCommand);
adpt.Fill(ds);
adpt.Dispose();
return ds;
}
catch (SqlException ex)
{
throw ex;
}
} /// <summary>
/// 获取DataSet 无参
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="myConn">数据库连接</param>
/// <returns>DataSet</returns>
public static DataSet GetDataSet(string strSql, SqlConnection myConn)
{ try
{
DataSet ds = new DataSet();
SqlCommand sqlCommand = GetSqlCommand(strSql, myConn, null);
SqlDataAdapter adpt = new SqlDataAdapter(sqlCommand);
adpt.Fill(ds);
adpt.Dispose();
return ds;
}
catch (SqlException ex)
{
throw ex;
}
} /// <summary>
/// 执行SQL,返回结果集中第一行第一列(带参数)
/// </summary>
/// <param name="sql">SQL语句</param>
/// <returns>object</returns>
public static object ExecuteScalar(string strSql, SqlConnection myConn, params SqlParameter[] cmdParms)
{
try
{
SqlCommand sqlCommand = GetSqlCommand(strSql, myConn, cmdParms);
object flag = sqlCommand.ExecuteScalar();
return flag;
}
catch (SqlException ex)
{
throw ex;
}
} /// <summary>
/// 执行SQL,返回结果集中第一行第一列(不带参数)
/// </summary>
/// <param name="sql">SQL语句</param>
/// <returns>object</returns>
public static object ExecuteScalar(string strSql, SqlConnection myConn)
{
try
{
SqlCommand sqlCommand = GetSqlCommand(strSql, myConn, null);
object flag = sqlCommand.ExecuteScalar();
return flag;
}
catch (SqlException ex)
{
throw ex;
}
}
/// <summary>
/// 获取DataTable带参
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="myConn">数据库连接</param>
/// <returns>DataSet</returns>
public static DataTable GetDataTable(string strSql, SqlConnection myConn, params SqlParameter[] cmdParms)
{
try
{
DataTable dt = new DataTable();
SqlCommand sqlCommand = new SqlCommand(); sqlCommand = GetSqlCommand(strSql, myConn, cmdParms);
SqlDataAdapter adpt = new SqlDataAdapter(sqlCommand);
adpt.Fill(dt);
adpt.Dispose();
return dt;
}
catch (SqlException ex)
{
throw ex;
}
}
/// <summary>
/// 获取DataTable 无参
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="myConn">数据库连接</param>
/// <returns>DataSet</returns>
public static DataTable GetDataTable(string strSql, SqlConnection myConn)
{
try
{
DataTable dt = new DataTable();
SqlCommand sqlCommand = new SqlCommand(); sqlCommand = GetSqlCommand(strSql, myConn, null);
SqlDataAdapter adpt = new SqlDataAdapter(sqlCommand);
adpt.Fill(dt);
adpt.Dispose();
return dt;
}
catch (SqlException ex)
{
throw ex;
}
} private static SqlCommand GetSqlCommand(string strSql, SqlConnection myConn, params SqlParameter[] cmdParms)
{
try
{
SqlCommand myComm = new SqlCommand();
//设置数据库连接
myComm.Connection = myConn;
//设置Sql语句
myComm.CommandText = strSql;
//设置Sql执行方式
myComm.CommandType = CommandType.Text;
//等待时间
myComm.CommandTimeout = ; if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
myComm.Parameters.Add(parameter);
}
}
return myComm;
}
catch (SqlException ex)
{
throw ex;
}
} public static void WriteLog(string sql, params SqlParameter[] cmdParms)
{
string straction = "";
string strtablename = "";
string strsql = sql.Trim(); if (strsql.ToLower().Trim().IndexOf("insert") == )
{
straction = "insert";
strtablename = sql.Trim().ToLower().Replace("insert", "").Trim().Replace("into", "").Trim().Split('(')[];
}
else if (strsql.ToLower().Trim().IndexOf("update") == )
{
straction = "update";
strtablename = sql.Trim().ToLower().Replace("update", "").Trim().Split(' ')[];
} if (cmdParms != null)
{
for (int i = ; i < cmdParms.Length; i++)
{
strsql = strsql.Replace(cmdParms[i].ParameterName, "'" + cmdParms [i].Value+ "'");
}
} SqlConnection conndef = ConnOpen("Default");
//写日志
int ilog = Convert.ToInt32(CommonClass.InsertSysLog(straction, "表:" + strtablename, strsql, conndef));//调用执行写系统日志
ConnClose(conndef);
} public static void WriteLog(string sql)
{
string straction = "";
string strtablename = "";
string strsql = sql.Trim(); if (strsql.ToLower().Trim().IndexOf("insert") == )
{
straction = "insert";
strtablename = sql.Trim().ToLower().Replace("insert", "").Trim().Replace("into", "").Trim().Split('(')[];
}
else if (strsql.ToLower().Trim().IndexOf("update") == )
{
straction = "update";
strtablename = sql.Trim().ToLower().Replace("update", "").Trim().Split(' ')[];
} SqlConnection conndef = ConnOpen("Default");
//写日志
int ilog = Convert.ToInt32(CommonClass.InsertSysLog(straction, "表:" + strtablename, strsql, conndef));//调用执行写系统日志
ConnClose(conndef);
} #endregion #region 存储过程 /// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static DataTable RunProcedure(SqlConnection conn, string storedProcName, IDataParameter[] parameters)
{
try
{
DataSet dataSet = new DataSet();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(conn, storedProcName, parameters);
sqlDA.Fill(dataSet);
return dataSet.Tables[];
}
catch (Exception ex)
{ return null;
}
} /// <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, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
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;
} #endregion #region 事物操作
/// <summary>
/// 跨库事物处理
/// </summary>
/// <param name="SqlList"></param>
/// <returns></returns>
public static int ExecuteSqlTranEx(IList<CommandInfo> SqlList)
{
int result = ;
try
{
using (TransactionScope scope = new TransactionScope())
{
for (int i = ; i < SqlList.Count; i++)
{
SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings[SqlList[i].ConnStr].ConnectionString);
using (myConn)
{
myConn.Open();
SqlCommand myComm = GetSqlCommand(SqlList[i].Sql, myConn, SqlList[i].Parameters);
int r = myComm.ExecuteNonQuery();
result += ;
myConn.Dispose();
myConn.Close(); }
scope.Complete(); //提交事物
}
}
}
catch (Exception ex) //发生异常后自动回滚
{
//throw;
}
return result;
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的IList,Sql为CommandInfo.Sql,SqlParameter为CommandInfo.Parameters</param>
public static int ExecuteSqlTran(IList<CommandInfo> SqlList, SqlConnection SqlDrConn)
{ //当连接处于打开状态时关闭,然后再打开,避免有时候数据不能及时更新
if (SqlDrConn.State == ConnectionState.Open)
{
SqlDrConn.Close();
}
SqlDrConn.Open();
using (SqlTransaction trans = SqlDrConn.BeginTransaction())
{
SqlCommand sqlCommand = new SqlCommand();
try
{
//受影响总条数
int count = ;
//循环
foreach (CommandInfo myDE in SqlList)
{
string sql = myDE.Sql;
SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
sqlCommand = GetSqlCommand(sql, SqlDrConn, cmdParms);
sqlCommand.Transaction = trans;
int val = sqlCommand.ExecuteNonQuery();
if (val == )
{
trans.Rollback();
return ;
}
count += val;
sqlCommand.Parameters.Clear();
}
trans.Commit();
return count;
}
catch
{
trans.Rollback();
throw;
}
}
}
#endregion }
public class CommandInfo
{
public CommandInfo(string strSql, SqlParameter[] cmdParameters, string strconn)
{
this.Sql = strSql;
this.Parameters = cmdParameters;
this.ConnStr = strconn;
}
public CommandInfo(string strSql, SqlParameter[] cmdParameters)
{
this.Sql = strSql;
this.Parameters = cmdParameters;
}
/// <summary>
/// Sql语句
/// </summary>
public string Sql { set; get; }
/// <summary>
/// Sql参数
/// </summary>
public SqlParameter[] Parameters { set; get; }
/// <summary>
/// 数据库链接字符串 说明 跨库事务执行时使用
/// </summary>
public string ConnStr { set; get; }
}
}
-->
<configuration>
<connectionStrings>
<clear/>
<!--开发库-->
<add name="Default" connectionString="Data Source=211.149.217.181;Initial Catalog=DevFotileEcBossDB;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="MemberDB" connectionString="Data Source=211.149.217.181;Initial Catalog=DevMemberDB;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="WEBDB" connectionString="Data Source=211.149.217.181;Initial Catalog=DevWebDB;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="webadDB" connectionString="Data Source=211.149.217.181;Initial Catalog=ECwebadDB;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="CRMDB" connectionString="Data Source=211.149.217.181;Initial Catalog=ECCRMDB;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="ECSMS" connectionString="Data Source=211.149.217.181;Initial Catalog=ftSMS;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="CIOKMDB" connectionString="Data Source=211.149.217.181;Initial Catalog=CIOKMDB;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="SPSDB" connectionString="Data Source=211.149.217.181;Initial Catalog=DevSNSResourceDB;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="LOGDB" connectionString="Data Source=211.149.217.181;Initial Catalog=DevFotileEcBossDB;User ID=sa;Password=ft!@12" providerName="System.Data.SqlClient"/>
<add name="WDGJDB" connectionString="Data Source=211.149.197.100;Initial Catalog=WDGJDB;User ID=readonlysa;Password=ft!@12" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<add key="authorizedSequence" value="2c9f62803bcc4478bb3fe6ea227cb7d3"/>
</appSettings>
DBHerperl类的更多相关文章
- Java类的继承与多态特性-入门笔记
相信对于继承和多态的概念性我就不在怎么解释啦!不管你是.Net还是Java面向对象编程都是比不缺少一堂课~~Net如此Java亦也有同样的思想成分包含其中. 继承,多态,封装是Java面向对象的3大特 ...
- C++ 可配置的类工厂
项目中常用到工厂模式,工厂模式可以把创建对象的具体细节封装到Create函数中,减少重复代码,增强可读和可维护性.传统的工厂实现如下: class Widget { public: virtual i ...
- Android请求网络共通类——Hi_博客 Android App 开发笔记
今天 ,来分享一下 ,一个博客App的开发过程,以前也没开发过这种类型App 的经验,求大神们轻点喷. 首先我们要创建一个Andriod 项目 因为要从网络请求数据所以我们先来一个请求网络的共通类. ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
- ASP.NET Core 折腾笔记二:自己写个完整的Cache缓存类来支持.NET Core
背景: 1:.NET Core 已经没System.Web,也木有了HttpRuntime.Cache,因此,该空间下Cache也木有了. 2:.NET Core 有新的Memory Cache提供, ...
- .NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类
.NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类 0x00 为什么要引入扩展方法 有的中间件功能比较简单,有的则比较复杂,并且依赖其它组件.除 ...
- Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- PHP-解析验证码类--学习笔记
1.开始 在 网上看到使用PHP写的ValidateCode生成验证码码类,感觉不错,特拿来分析学习一下. 2.类图 3.验证码类部分代码 3.1 定义变量 //随机因子 private $char ...
- C# 多种方式发送邮件(附帮助类)
因项目业务需要,需要做一个发送邮件功能,查了下资料,整了整,汇总如下,亲测可用- QQ邮箱发送邮件 #region 发送邮箱 try { MailMessage mail = new MailMess ...
随机推荐
- Visual Studio 2015开发Android App问题集锦
Visual Studio 2015开发Android App 启动调试始终无法完成应用部署的解决方案 创建一个Android App项目后,直接启动调试发现Visual Studio Emulato ...
- zookeeper初体验之关于解决quartz重复执行任务的一种思路
前阵子工作中遇到了一个很麻烦的问题.本人所在的项目组做了一个机遇quartz集群的任务系统.通俗点讲就是用quartz框架(quartz是一款能跑定时任务的框架支持复杂的时间表达式)来执行定时任务.但 ...
- POJ3662 Telephone Lines( dijkstral + 二分 )
POJ3662 Telephone Lines 题目大意:要在顶点1到顶点n之间建一条路径,假设这条路径有m条边,其中有k条边是免费的,剩余m-k条边是要收费的, 求这m-k条边中花费最大的一条边的最 ...
- 使用自定义类型做qmap,qhash的key
map在STL中的定义 template <class Key, class T, class Compare = less<Key>, class Alloc = alloc> ...
- $().text() 和 $().html()
1:性能 stackflow:http://stackoverflow.com/questions/1910794/what-is-the-difference-between-jquery-text ...
- memcached全面剖析
memcached介绍如今,越来越多的Web应用程序开始使用memcached这个高速的缓存服务器软件.然而,memcached的基础知识远远未能像其他Web技术那样普及,memcached在国内的大 ...
- dubbo No provider available for the service com.alibaba.dubbo.monitor.MonitorService from registry
No provider available for the service com.alibaba.dubbo.monitor.MonitorService from registry http:// ...
- IOC容器MEF在MVC中的使用
最近想把自己的网站框架用IOC改造下,经过对比,我初步选择autofac,虽然MEF不需要配置,但性能不行,autofac虽然需要自己写自动化注入,但性能非常好. 先分析下各大IOC框架的性能,分两类 ...
- OC .(点)与->(箭头)用法区别
这两天同学总是问OC里.和->的用法区别,当时回答的不是很好,周末查了一下,大概清楚了,在这里记录一笔. 先看这个例程 #import <Foundation/Foundation.h&g ...
- Codeforces 459E Pashmak and Graph
http://www.codeforces.com/problemset/problem/459/E 题意: 给出n个点,m条边的有向图,每个边有边权,求一条最长的边权上升的路径的长度. 思路:用f存 ...