自己写的一个工具类,主要是业务场景的需要。
主要有两个功能:
调用方式
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name="sql">需要执行的sql语句</param>
public bool ExecuteSql(string sql, ref string errorMsg)
{
SetConnOpen();
string[] sqls = serializeSql(sql);
OleDbTransaction tran = conn.BeginTransaction();
try
{
comm = new OleDbCommand();
comm.Transaction = tran;
comm.Connection = conn;
foreach (string s in sqls)
{
var temps = s.Trim().Replace("\r\n", "");
if (!string.IsNullOrEmpty(temps))
{
comm.CommandText = temps;
comm.ExecuteNonQuery();
}
}
tran.Commit();
return true;
}
catch(Exception ex)
{
tran.Rollback();
errorMsg = ex.Message;
return false;
}
finally
{
conn.Close();
}
}
执行包含sql语句的字符串
/// <summary>
/// 从sql脚本文件执行
/// </summary>
/// <param name="sqlFilePath">sql脚本文件的路径</param>
/// <returns></returns>
public bool ExecuteSqlByFile(string sqlFilePath,ref string errorMsg)
{
if(!File.Exists(sqlFilePath))
{
throw new FileNotFoundException("未找到该sql脚本,请检查路径是否错误");
} string sourceSql = new StreamReader(sqlFilePath).ReadToEnd();
string[] sqls = serializeSql(sourceSql);
SetConnOpen();
OleDbTransaction tran = conn.BeginTransaction();
try
{
comm = new OleDbCommand();
comm.Transaction = tran;
comm.Connection = conn;
foreach (string s in sqls)
{
var temps = s.Trim().Replace("\r\n", "");
if (!string.IsNullOrEmpty(temps))
{
comm.CommandText = temps;
comm.ExecuteNonQuery();
}
}
tran.Commit();
return true;
}
catch (Exception ex)
{
tran.Rollback();
errorMsg = ex.Message;
return false;
}
finally
{
conn.Close();
}
}
/// <summary>
/// 将sql脚本进行序列化
/// </summary>
/// <param name="sql">sql脚本</param>
/// <returns></returns>
private string[] serializeSql(string sql)
{
string[] ss = sql.Split(new string[] { "/*go*/" }, StringSplitOptions.RemoveEmptyEntries);
return ss;
}
执行包含sql语句的文件
其实思路比较简单,就是将sql语句用字符串进行分割,然后将一条条sql语句组合成一个数组,依次进行执行即可。在执行过程中使用事务处理,当错误发生时,能够进行回滚操作。下面是完整代码:
AccessUtils.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.OleDb;
using System.Data.OleDb;
using System.IO;
using System.Data; namespace AccessRuntime.Bin
{
/// <summary>
/// Access工具类
/// </summary>
internal sealed class AccessUtils
{
/// <summary>
/// access数据库连接字符串
/// </summary>
private string accessConnectionString = string.Empty;
/// <summary>
/// access数据库连接对象
/// </summary>
private OleDbConnection conn;
/// <summary>
/// access数据库命令对象
/// </summary>
private OleDbCommand comm;
/// <summary>
/// access数据库连接字符串
/// </summary>
public string AccessConnectionString
{
get {
if (!string.IsNullOrEmpty(accessConnectionString))
return accessConnectionString;
else
{
string connstr = ConfigurationManager.ConnectionStrings["AccessRuntimeConnectionString"].ConnectionString;
if (string.IsNullOrEmpty(connstr))
throw new ConnectionStringElementNotFindException("未找到或未设置AccessRuntimeConnectionString节点");
else
return connstr;
}
}
}
/// <summary>
/// 初始化连接(有密码)
/// </summary>
/// <param name="filepath">可以为空,为空则调用配置文件</param>
/// <param name="pwd">数据库密码</param>
/// <example>
/// public AccessUtils("123",null)
/// </example>
public AccessUtils(string pwd,string filepath)
{
if (string.IsNullOrEmpty(filepath))
{
filepath = AccessConnectionString;
}
this.conn = new OleDbConnection(filepath + "; Jet OLEDB:Database Password=" + pwd);
conn.Open();
} /// <summary>
/// 初始化连接(无密码)
/// </summary>
/// <param name="filepath"></param>
/// <example>
/// 1.public AccessUtils(filepath)
/// 2.public AccessUtils()//不传递参数则调用配置文件
/// </example>
public AccessUtils(string filepath = null)
{
if (string.IsNullOrEmpty(filepath))
{
filepath = AccessConnectionString;
}
this.conn = new OleDbConnection(filepath);
conn.Open();
} /// <summary>
/// 执行sql语句
/// </summary>
/// <param name="sql">需要执行的sql语句</param>
public bool ExecuteSql(string sql, ref string errorMsg)
{
SetConnOpen();
string[] sqls = serializeSql(sql);
OleDbTransaction tran = conn.BeginTransaction();
try
{
comm = new OleDbCommand();
comm.Transaction = tran;
comm.Connection = conn;
foreach (string s in sqls)
{
var temps = s.Trim().Replace("\r\n", "");
if (!string.IsNullOrEmpty(temps))
{
comm.CommandText = temps;
comm.ExecuteNonQuery();
}
}
tran.Commit();
return true;
}
catch(Exception ex)
{
tran.Rollback();
errorMsg = ex.Message;
return false;
}
finally
{
conn.Close();
}
}
/// <summary>
/// 从sql脚本文件执行
/// </summary>
/// <param name="sqlFilePath">sql脚本文件的路径</param>
/// <returns></returns>
public bool ExecuteSqlByFile(string sqlFilePath,ref string errorMsg)
{
if(!File.Exists(sqlFilePath))
{
throw new FileNotFoundException("未找到该sql脚本,请检查路径是否错误");
} string sourceSql = new StreamReader(sqlFilePath).ReadToEnd();
string[] sqls = serializeSql(sourceSql);
SetConnOpen();
OleDbTransaction tran = conn.BeginTransaction();
try
{
comm = new OleDbCommand();
comm.Transaction = tran;
comm.Connection = conn;
foreach (string s in sqls)
{
var temps = s.Trim().Replace("\r\n", "");
if (!string.IsNullOrEmpty(temps))
{
comm.CommandText = temps;
comm.ExecuteNonQuery();
}
}
tran.Commit();
return true;
}
catch (Exception ex)
{
tran.Rollback();
errorMsg = ex.Message;
return false;
}
finally
{
conn.Close();
}
}
/// <summary>
/// 将sql脚本进行序列化
/// </summary>
/// <param name="sql">sql脚本</param>
/// <returns></returns>
private string[] serializeSql(string sql)
{
string[] ss = sql.Split(new string[] { "/*go*/" }, StringSplitOptions.RemoveEmptyEntries);
return ss;
}
/// <summary>
/// 获取打开的连接
/// </summary>
private void SetConnOpen()
{
if (this.conn.State != ConnectionState.Open)
{
this.conn.Open();
}
}
}
}
AccessUtils.cs
AccessTool.cs 这个是对AccessUtils类的封装,提供了更加友好的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace AccessRuntime.Bin
{
/// <summary>
/// Access工具
/// 注意:语句之间使用 /*go*/ 进行分割
/// </summary>
public static class AccessTool
{
/// <summary>
/// 在Access数据库中执行sql语句
/// </summary>
/// <param name="sql">sql脚本</param>
/// <param name="pwd">数据库密码(如果无密码则不填写此参数)</param>
/// <returns>执行结果</returns>
public static bool ExecuteSql(string sql,string pwd = null)
{
AccessUtils au = null;
if (string.IsNullOrEmpty(pwd)) {
au = new AccessUtils();
string msg = null;
if(au.ExecuteSql(sql, ref msg))
{
return true;
}
else
{
throw new AccessRuntimeException(msg);
}
}
else
{
au = new AccessUtils(pwd, null);
string msg = null;
if(au.ExecuteSql(sql,ref msg))
{
return true;
}
else
{
throw new AccessRuntimeException(msg);
}
} } /// <summary>
/// 在Access数据库中执行sql脚本
/// </summary>
/// <param name="sqlpath">sql脚本路径</param>
/// <param name="pwd">数据库密码(如果无密码则不填写此参数)</param>
/// <returns>执行结果</returns>
public static bool ExecuteSqlByFile(string sqlpath,string pwd = null)
{
AccessUtils au = null;
//判断密码是否填写
if (string.IsNullOrEmpty(pwd))
{
au = new AccessUtils();
string msg = null;
if (au.ExecuteSqlByFile(sqlpath, ref msg))
{
return true;
}
else
{
throw new AccessRuntimeException(msg);
}
}
else
{
au = new AccessUtils(pwd, null);
string msg = null;
if (au.ExecuteSqlByFile(sqlpath, ref msg))
{
return true;
}
else
{
throw new AccessRuntimeException(msg);
}
}
} /// <summary>
/// 在指定Access数据库中执行sql语句
/// </summary>
/// <param name="sql">sql脚本</param>
/// <param name="dbpath">数据库所在路径</param>
/// <param name="pwd">执行结果</param>
/// <returns></returns>
public static bool OnExecuteSql(string sql,string dbpath,string pwd = null)
{
AccessUtils au = null;
if (string.IsNullOrEmpty(pwd))
{
au = new AccessUtils(dbpath);
string msg = null;
if (au.ExecuteSql(sql, ref msg))
{
return true;
}
else
{
throw new AccessRuntimeException(msg);
}
}
else
{
au = new AccessUtils(pwd, dbpath);
string msg = null;
if (au.ExecuteSql(sql, ref msg))
{
return true;
}
else
{
throw new AccessRuntimeException(msg);
}
} } /// <summary>
/// 在指定Access数据库中执行sql语句
/// </summary>
/// <param name="sqlpath">sql脚本路径</param>
/// <param name="dbpath">数据库所在路径</param>
/// <param name="pwd">执行结果</param>
/// <returns></returns>
public static bool OnExecuteSqlByFile(string sqlpath, string dbpath, string pwd = null)
{
AccessUtils au = null;
//判断密码是否填写
if (string.IsNullOrEmpty(pwd))
{
au = new AccessUtils(dbpath);
string msg = null;
if (au.ExecuteSqlByFile(sqlpath, ref msg))
{
return true;
}
else
{
throw new AccessRuntimeException(msg);
}
}
else
{
au = new AccessUtils(pwd, dbpath);
string msg = null;
if (au.ExecuteSqlByFile(sqlpath, ref msg))
{
return true;
}
else
{
throw new AccessRuntimeException(msg);
}
}
}
}
}
AccessToo.cs
本工具中还定义了两个自定义的异常类:AccessRuntimeException.cs,ConnectionStringElementNotFindException.cs,下付代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace AccessRuntime.Bin
{
/// <summary>
/// AccessRuntime异常
/// </summary>
public class AccessRuntimeException:Exception
{
/// <summary>
/// 配置文件节点未找到
/// </summary>
public AccessRuntimeException()
{ }
/// <summary>
/// 配置文件节点未找到
/// </summary>
/// <param name="message">异常信息</param>
public AccessRuntimeException(string message):base(message)
{ }
/// <summary>
///
/// </summary>
/// <param name="message">异常信息</param>
/// <param name="inner">异常类</param>
public AccessRuntimeException(string message, Exception inner)
: base(message, inner)
{ }
}
}
AccessRuntimeException.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace AccessRuntime.Bin
{
/// <summary>
/// 配置文件节点未找到
/// </summary>
internal class ConnectionStringElementNotFindException:Exception
{
/// <summary>
/// 配置文件节点未找到
/// </summary>
public ConnectionStringElementNotFindException()
{ }
/// <summary>
/// 配置文件节点未找到
/// </summary>
/// <param name="message">异常信息</param>
public ConnectionStringElementNotFindException(string message):base(message)
{ }
/// <summary>
///
/// </summary>
/// <param name="message">异常信息</param>
/// <param name="inner">异常类</param>
public ConnectionStringElementNotFindException(string message, Exception inner)
: base(message, inner)
{ }
}
}
ConnectionStringElementNotFindException.cs
注意:
1.使用本代码时,需要配置config文件,需要添加AccessRuntimeConnectionString的ConnectionString节点,进行Access数据库配置,当然你也可以根据自己的需要进行调整。
2.在本工具中各个sql语句间使用/*go*/进行分隔,类似mssql中的go(批处理)一样。