Web.config中代码

<configuration>
<connectionStrings>
<add name="connString" connectionString="Server=数据库服务;DataBase=数据库名称;Uid=数据库登录名用户;Pwd=数据库登录密码"/>
</connectionStrings>
</configuration>

现在我们先建一个SQLHelper类,用来对数据库的操作

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration; namespace DAL
{
/// <summary>
/// 针对SQLServer数据库的通用访问类
/// </summary>
public class SQLHelper
{ //封装数据库连接字符串
private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString(); #region 封装格式化SQL语句执行的各种方法 public static int Update(string sql)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//将异常信息写入日志
string errorInfo = "调用public static int Update(string sql)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
conn.Close();
}
}
public static object GetSingleResult(string sql)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
return cmd.ExecuteScalar();
}
catch (Exception ex)
{
//将异常信息写入日志
string errorInfo = "调用public static object GetSingleResult(string sql)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
conn.Close();
}
}
public static SqlDataReader GetReader(string sql)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
conn.Close();
//将异常信息写入日志
string errorInfo = "调用SqlDataReader GetReader(string sql)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
}
public static DataSet GetDataSet(string sql)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);//创建数据适配器对象
DataSet ds = new DataSet();//创建一个内存数据集
try
{
conn.Open();
da.Fill(ds);//使用数据适配器填充数据集
return ds;
}
catch (Exception ex)
{
//将异常信息写入日志
string errorInfo = "调用 public static DataSet GetDataSet(string sql)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
conn.Close();
}
}
public static bool UpdateByTran(List<string> sqlList)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
try
{
conn.Open();
cmd.Transaction = conn.BeginTransaction();//开启事务
foreach (string sql in sqlList)
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
cmd.Transaction.Commit();//提交事务
return true;
}
catch (Exception ex)
{
if (cmd.Transaction != null)
{
cmd.Transaction.Rollback();//回滚事务
}
string errorInfo = "调用UpdateByTran(List<string> sqlList)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
if (cmd.Transaction != null)
{
cmd.Transaction = null;//清空事务
}
conn.Close();
}
} #endregion #region 封装带参数SQL语句执行的各种方法 public static int Update(string sql, SqlParameter[] param)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Parameters.AddRange(param);//封装参数
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string errorInfo = "调用 public static int Update(string sql,SqlParameter[] param)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw ex;
}
finally
{
conn.Close();
}
}
public static object GetSingleResult(string sql, SqlParameter[] param)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Parameters.AddRange(param);//封装参数
return cmd.ExecuteScalar();
}
catch (Exception ex)
{
//将异常信息写入日志
string errorInfo = "调用 public static object GetSingleResult(string sql, SqlParameter[] param)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
conn.Close();
}
}
public static SqlDataReader GetReader(string sql, SqlParameter[] param)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Parameters.AddRange(param);//封装参数
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
conn.Close();
//将异常信息写入日志
string errorInfo = "调用 public static SqlDataReader GetReader(string sql, SqlParameter[] param)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
}
/// <summary>
/// 启用事务提交多条带参数的SQL语句
/// </summary>
/// <param name="mainSql">主表SQL语句</param>
/// <param name="mainParam">主表SQL语句对应的参数</param>
/// <param name="detailSql">明细表SQL语句</param>
/// <param name="detailParam">明细表SQL语句对应的参数数组集合</param>
/// <returns>返回事务是否执行成功</returns>
public static bool UpdateByTran(string mainSql, SqlParameter[] mainParam,
string detailSql, List<SqlParameter[]> detailParam)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
try
{
conn.Open();
cmd.Transaction = conn.BeginTransaction();//开启事务
if (mainSql != null && mainSql.Length != )
{
cmd.CommandText = mainSql;
cmd.Parameters.AddRange(mainParam);
cmd.ExecuteNonQuery();
}
foreach (SqlParameter[] param in detailParam)
{
cmd.CommandText = detailSql;
cmd.Parameters.Clear();//必须要清除以前的参数
cmd.Parameters.AddRange(param);
cmd.ExecuteNonQuery();
}
cmd.Transaction.Commit();//提交事务
return true;
}
catch (Exception ex)
{
if (cmd.Transaction != null)
{
cmd.Transaction.Rollback();//回滚事务
}
string errorInfo = "调用 public static bool UpdateByTran(string mainSql, SqlParameter[] mainParam, string detailSql, List<SqlParameter[]> detailParam)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
if (cmd.Transaction != null)
{
cmd.Transaction = null;//清空事务
}
conn.Close();
}
} #endregion #region 封装调用存储过程执行的各种方法 public static int UpdateByProcedure(string spName, SqlParameter[] param)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(spName, conn);
try
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;//声明当前操作是存储过程
cmd.Parameters.AddRange(param);//封装参数
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string errorInfo = "调用 public static int UpdateByProcedure(string spName, SqlParameter[] param)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
conn.Close();
}
}
public static object GetSingleResultByProcedure(string spName, SqlParameter[] param)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(spName, conn);
try
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(param);//封装参数
return cmd.ExecuteScalar();
}
catch (Exception ex)
{
//将异常信息写入日志
string errorInfo = "调用 public static object GetSingleResult(string sql, SqlParameter[] param)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
conn.Close();
}
}
public static SqlDataReader GetReaderByProcedure(string spName, SqlParameter[] param)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(spName, conn);
try
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(param);//封装参数
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
conn.Close();
//将异常信息写入日志
string errorInfo = "调用 public static SqlDataReader GetReader(string sql, SqlParameter[] param)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
}
/// <summary>
/// 启用事务调用带参数的存储过程
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="paramArray">存储过程参数数组集合</param>
/// <returns>返回基于事务的存储过程调用是否成功</returns>
public static bool UpdateByTran(string procedureName, List<SqlParameter[]> paramArray)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
try
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;//声明当前操作是调用存储过程
cmd.CommandText = procedureName;
cmd.Transaction = conn.BeginTransaction();//开启事务
foreach (SqlParameter[] param in paramArray)
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(param);
cmd.ExecuteNonQuery();
}
cmd.Transaction.Commit();//提交事务
return true;
}
catch (Exception ex)
{
if (cmd.Transaction != null)
{
cmd.Transaction.Rollback();//回滚事务
}
string errorInfo = "调用 public static bool UpdateByTran(string procedureName,List<SqlParameter[]>paramArray)方法时发生错:" + ex.Message;
WriteLog(errorInfo);
throw new Exception(errorInfo);
}
finally
{
if (cmd.Transaction != null)
{
cmd.Transaction = null;//清空事务
}
conn.Close();
}
} #endregion #region 其他方法 private static void WriteLog(string log)
{
FileStream fs = new FileStream("sqlhelper.log", FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now.ToString() + " " + log);
sw.Close();
fs.Close();
} #endregion
}
}

WriteLog方法主要是用来记录错误日志,把错误已文本的方式存储在根目录里方便维护,

同时在SQLHelper要引用System.Configuration命名空间,不然的话会报错。

针对SQLServer数据库的通用访问类的更多相关文章

  1. C#操作SqlServer MySql Oracle通用帮助类

    C#操作SqlServer MySql Oracle通用帮助类 [前言] 作为一款成熟的面向对象高级编程语言,C#在ADO.Net的支持上已然是做的很成熟,我们可以方便地调用ADO.Net操作各类关系 ...

  2. C#操作SqlServer MySql Oracle通用帮助类Db_Helper_DG(默认支持数据库读写分离、查询结果实体映射ORM)

    [前言] 作为一款成熟的面向对象高级编程语言,C#在ADO.Net的支持上已然是做的很成熟,我们可以方便地调用ADO.Net操作各类关系型数据库,在使用了多年的Sql_Helper_DG后,由于项目需 ...

  3. [C#]记录一次异常排查,关于using语法、sqlserver数据库session、DBHelper类

    最近在做一个基于asp.net和sqlserver的网站项目,发现网站运行一段时间之后,会报异常: 超时时间已到,但是尚未从池中获取连接.出现这种情况可能是因为所有池连接均在使用,并且达到了最大池大小 ...

  4. java操作数据库的通用的类

    package cn.dao; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; ...

  5. SQLServer数据库通用访问类

    private static string connString=ConfigurationManager.ConnStrings["connString"].ToString() ...

  6. 自己写的访问SqlServer数据库的通用DAL层

    如题,直接贴代码. 首先是DataTable转List<T>的方法,这个方法通用性极强. #region Table转List /// <summary> /// Table转 ...

  7. C#:数据库通用访问类 SqlHelper

    using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; usin ...

  8. asp.net针对SQLSERVER数据库备份和恢复的一揽子问题解决

    一.备份 先备份到服务端,用gridview显示出来,点击可以下载到本地 二.恢复 这是很麻烦的事情,本人查阅不少资料,耗费不少时间才搞定. 直接恢复数据库时不行的,会提示数据库正在使用,恢复失败等信 ...

  9. Ado.net 通用访问类

    public class DbHelperSQL { private static string connString = ConfigurationManager.ConnectionStrings ...

随机推荐

  1. sql多表更新使用别名(小技巧)

    update     A set     A.CityRegionID=B.ParentID,     A.CityName=(select RegionName from Common_Region ...

  2. canvas变换

    canvas变换 方法 save() 保存canvas状态 restore() 回复canvas保存的状态 translate(x, y) 移动canvas位置 rotate(radians) 顺时针 ...

  3. IDEA 配置Jrebet 自动加载Java类,

    官方文档地址: http://manuals.zeroturnaround.com/jrebel/ide/intellij.html#installation 过期激活 https://blog.cs ...

  4. 使用D3D渲染YUV视频数据<转>

    源代码下载 转载地址:http://blog.csdn.net/dengzikun/article/details/5824874 源码地址:http://download.csdn.net/down ...

  5. 迷你MVVM框架 avalonjs 学习教程1、引入avalon

    avalon是国内最强大的MVVM框架,没有之一,虽然淘宝KISSY团队也搞了两个MVVM框架,但都无疾而终.其他的MVVM框架都没几个.也只有外国人与像我这样闲的架构师才有时间钻研这东西.我很早之前 ...

  6. Python列表练习题

    1.创建一个空列表,命名为names,往里面添加 Lihua.Rain.Jack.Xiuxiu.Peiqi和Black元素. #!-*- coding:utf-8 -*- names = [" ...

  7. linux 使用systemctl 启动服务报错: Error: No space left on device

    By default, Linux only allocates 8192 watches for inotify, which is ridiculously low. And when it ru ...

  8. sdc-docker

    ssh root@109.105.7.96 sdc-login docker /opt/smartdc/docker ls /var/svc/log/ cat smartdc-application- ...

  9. overloading与overriding的区别

    overloading: “重载”,参数和返回值可改变. overriding: “覆盖”,重写父类的虚函数,参数和返回值必须与父类相同. 重写Overriding是父类与子类之间多态性的一种表现,重 ...

  10. Unity5 Shader Stripping 导致 LightMap 全部丢失的解决方法

    当使用 SceneManager.LoadScene 的时候,会自动载入LightMap 和 NavMesh的数据.然后再对MeshRender 进行指定 LightMapIndex 以及 Light ...