DataAccess SqlHelper


   /// <summary>
/// 数据访问基类
/// </summary>
public abstract class DataAccess : MarshalByRefObject
{
/// <summary>
/// LifetimeService
/// </summary>
/// <returns>object</returns>
public override object InitializeLifetimeService()
{
return null;
}

protected string cnnstr = "";
protected DataAccess()
{

}

/// <summary>
/// 获取压缩传输DataTable
/// </summary>
/// <param name="aSQL">SQL</param>
/// <param name="aParameters">Parameters</param>
/// <returns>byte[]</returns>
public byte[] GetTableData(string aSQL, Dictionary<string, object> aParameters)
{
return DataCompression.CompressionDataTable(GetDataTable(aSQL,aParameters));
}

/// <summary>
/// 保存压缩数据表
/// </summary>
/// <param name="aDataTable">DataTable</param>
/// <param name="aSQL">Sql</param>
/// <returns>int</returns>
public int SaveDataTable(byte[] aDataTable, string aSQL)
{
return SaveTable(DataCompression.DecompressionXmlDataTable(aDataTable), aSQL);
}

/// <summary>
/// 创建System.Data.Common.DbCommand
/// </summary>
/// <param name="sql">sql</param>
/// <param name="parameters">Dictionary<string, object></param>
/// <returns>System.Data.Common.DbCommand</returns>
private System.Data.Common.DbCommand GetCommand(System.Data.Common.DbConnection connection, string aSQL, Dictionary<string, object> aParameters = null)
{
System.Data.Common.DbCommand cmd = connection.CreateCommand();
cmd.CommandText = Application.SQLStatementOpr.PrepareQuery(aSQL);
if (aParameters != null)
{
foreach (KeyValuePair<string, object> item in aParameters)
{
System.Data.Common.DbParameter parameter = cmd.CreateParameter();
parameter.ParameterName = item.Key;
parameter.Value = item.Value;
cmd.Parameters.Add(parameter);
}
}
return cmd;
}

#region DataAccess Command
/// <summary>
/// 新型查询
/// </summary>
/// <param name="aSQL">sql</param>
/// <param name="aParameters"> Dictionary参数</param>
/// <returns>影响行数</returns>
public int ExcuteCommand(string aSQL, Dictionary<string, object> aParameters)
{
try
{
using (System.Data.Common.DbConnection connection = CreateConnection())
{
Authorize(aSQL);
connection.Open();
return GetCommand(connection, aSQL, aParameters).ExecuteNonQuery();
}
}
catch (Exception e)
{
throw new Exception("ExcuteCommand error of : " + e.Message + aSQL, e);
}
}

/// <summary>
/// 返回第一行第一列值or Null
/// </summary>
/// <param name="aSQL">sql</param>
/// <returns>object</returns>
public object ExecuteScalar(string aSQL)
{
return ExecuteScalar(aSQL, null);
}

/// <summary>
/// 返回第一行第一列值or Null
/// </summary>
/// <param name="aSQL">sql</param>
/// <param name="aParameters">Dictionary参数</param>
/// <returns>object</returns>
public object ExecuteScalar(string aSQL, Dictionary<string, object> aParameters)
{
try
{
using (System.Data.Common.DbConnection connection = CreateConnection())
{
Authorize(aSQL);
connection.Open();
return GetCommand(connection, aSQL, aParameters).ExecuteScalar();
}
}
catch (Exception e)
{
throw new Exception("ExecuteScalar error of : " + e.Message + aSQL, e);
}
}

/// <summary>
/// 查询返回DbDataReader
/// </summary>
/// <param name="aSQL">sql</param>
/// <param name="aParameters">Dictionary参数</param>
/// <returns>System.Data.Common.DbDataReader</returns>
public System.Data.Common.DbDataReader ExecuteReader(string aSQL, Dictionary<string, object> aParameters)
{
System.Data.Common.DbConnection connection = CreateConnection();
connection.Open();
return GetCommand(connection, aSQL, aParameters).ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aDataTable">DataTable</param>
/// <param name="aSQL">sql</param>
/// <returns>影响行数</returns>
public int Fill(System.Data.DataTable aDataTable, string aSQL)
{
return Fill(aDataTable, aSQL, null);
}

/// <summary>
/// 使用TableName填充
/// </summary>
/// <param name="aDataTable">DataTable</param>
/// <returns>影响行数</returns>
public int Fill(System.Data.DataTable aDataTable)
{
return Fill(aDataTable, "select * from " + aDataTable.TableName);
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aDataTable">DataTable</param>
/// <param name="aSQL">sql</param>
/// <param name="aParameters">Dictionary</param>
/// <returns>影响行数</returns>
public int Fill(System.Data.DataTable aDataTable, string aSQL, Dictionary<string, object> aParameters)
{
try
{
using (System.Data.Common.DbConnection connection = CreateConnection())
{
Authorize(aSQL);
connection.Open();
System.Data.Common.DbDataAdapter adapter = CreateAdapter();
adapter.SelectCommand = GetCommand(connection, aSQL, aParameters);
//adapter.MissingSchemaAction = System.Data.MissingSchemaAction.AddWithKey; //David 2014-5-1
return adapter.Fill(aDataTable);
}
}
catch (Exception e)
{
throw new Exception("FillDataTable error of : " + e.Message + aSQL, e);
}
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aSQL">sql</param>
/// <returns>DataSet</returns>
public System.Data.DataSet GetDataSet(string aSQL)
{
return GetDataSet(aSQL, null);
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aSQL">sql</param>
/// <param name="aParameters">Dictionary</param>
/// <returns>DataSet</returns>
public System.Data.DataSet GetDataSet(string aSQL, Dictionary<string, object> aParameters)
{
System.Data.DataSet ds = new System.Data.DataSet();
FillDataSet(ds, aSQL, aParameters);
return ds;
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aDataSet">DataSet</param>
/// <returns>影响行数</returns>
public int FillDataSet(System.Data.DataSet aDataSet)
{
int iReturn = 0;
for (int i = 0; i < aDataSet.Tables.Count; i++)
{
System.Data.DataTable dt = aDataSet.Tables[i];
iReturn += Fill(dt);
}
return iReturn;
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aDataSet">DataSet</param>
/// <param name="aSQL">sql</param>
/// <returns>影响行数</returns>
public int FillDataSet(System.Data.DataSet aDataSet, string aSQL)
{
return FillDataSet(aDataSet, aSQL, null);
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aDataSet"></param>
/// <param name="aSQL">sql</param>
/// <param name="aParameters">Dictionary</param>
/// <returns>影响行数</returns>
public int FillDataSet(System.Data.DataSet aDataSet, string aSQL, Dictionary<string, object> aParameters)
{
using (System.Data.Common.DbConnection connection = CreateConnection())
{
connection.Open();
System.Data.Common.DbDataAdapter adapter = CreateAdapter();
adapter.SelectCommand = GetCommand(connection, aSQL, aParameters);
return adapter.Fill(aDataSet);
}
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aSQL">sql</param>
/// <returns>DataTable</returns>
public System.Data.DataTable GetDataTable(string aSQL)
{
return GetDataTable(aSQL, null);
}

/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aSQL">sql</param>
/// <returns>DataTable</returns>
public System.Data.DataTable GetSchema(string aSQL)
{

using (System.Data.Common.DbConnection connection = CreateConnection())
{
connection.Open();
return GetCommand(connection, aSQL).ExecuteReader(System.Data.CommandBehavior.SchemaOnly).GetSchemaTable();
}
}
/// <summary>
/// DbDataAdapter Fill DataTable
/// </summary>
/// <param name="aSQL">sql</param>
/// <param name="aParameters">Dictionary</param>
/// <returns>DataTable</returns>
public System.Data.DataTable GetDataTable(string aSQL, Dictionary<string, object> aParameters)
{
System.Data.DataTable dt = new System.Data.DataTable();
Fill(dt, aSQL, aParameters);
return dt;
}

/// <summary>
/// DbDataAdapter 保存 DataTable
/// </summary>
/// <param name="aDataTable">DataTable</param>
/// <returns>影响行数</returns>
public int SaveDataTable(System.Data.DataTable aDataTable)
{
return SaveDataTable(aDataTable, aDataTable.TableName);
}

/// <summary>
/// DbDataAdapter 保存 DataTable
/// </summary>
/// <param name="aDataTable">DataTable</param>
/// <param name="aTableName">TableName</param>
/// <returns>影响行数</returns>
public int SaveDataTable(System.Data.DataTable aDataTable, string aTableName)
{
return SaveTable(aDataTable, "select * from " + aTableName);
}

/// <summary>
/// DbDataAdapter 保存 DataTable
/// </summary>
/// <param name="aDataTable">DataTable</param>
/// <param name="aSQL">sql</param>
/// <returns>影响行数</returns>
public int SaveTable(System.Data.DataTable aDataTable, string aSQL)
{
using (System.Data.Common.DbConnection connection = CreateConnection())
{
connection.Open();
System.Data.Common.DbDataAdapter adapter = CreateAdapter();
adapter.SelectCommand = GetCommand(connection, aSQL, null);
System.Data.Common.DbCommandBuilder cmdBuild = CreateCommandBuilder();
cmdBuild.DataAdapter = adapter;
cmdBuild.QuotePrefix = "[";
cmdBuild.QuoteSuffix = "]";

System.Data.Common.DbCommand insertCommand = cmdBuild.GetInsertCommand(true);
System.Data.Common.DbCommand updateCommand = cmdBuild.GetUpdateCommand(true);
System.Data.Common.DbCommand deleteCommand = cmdBuild.GetDeleteCommand(true);
if (IsDefineCommandText)
{
updateCommand.CommandText = GenerateUpdateCommand(aDataTable, updateCommand.CommandText);
deleteCommand.CommandText = GenerateDeleteCommand(aDataTable, deleteCommand.CommandText);
}
cmdBuild.DataAdapter = null;
adapter.InsertCommand = insertCommand;
adapter.UpdateCommand = updateCommand;
adapter.DeleteCommand = deleteCommand;
return adapter.Update(aDataTable);
}
}

bool isDefineCommandText = false;
bool isGetedDefine = false;
/// <summary>
/// 是否使用自定义UpdateCommand
/// </summary>
public bool IsDefineCommandText
{
get
{
if (!isGetedDefine)
{
isDefineCommandText = System.Configuration.ConfigurationManager.AppSettings["DefineCommandText"] == "true";
isGetedDefine = true;
}
return isDefineCommandText;
}
}

/// <summary>
/// 仅根据主键及RecID进行更新
/// </summary>
/// <param name="aTable"></param>
/// <param name="aCommandText"></param>
/// <returns></returns>
private string GenerateDeleteCommand(System.Data.DataTable aTable, string aCommandText)
{
try
{
StringBuilder whereClauseBuilder = new StringBuilder();
foreach (System.Data.DataColumn key in aTable.PrimaryKey)
{
if (whereClauseBuilder.Length > 0)
whereClauseBuilder.Append(" AND ");
whereClauseBuilder.Append(string.Format(" [{0}] = @Original_{0}", key.ColumnName));
}

if (whereClauseBuilder.Length == 0)
return aCommandText;

int position = aCommandText.IndexOf("WHERE") + 5;
return aCommandText.Substring(0, position) + whereClauseBuilder.ToString();
}
catch
{
return aCommandText;
}
}

/// <summary>
/// 仅根据主键及RecID进行更新
/// </summary>
/// <param name="aTable"></param>
/// <param name="aCommandText"></param>
/// <returns></returns>
private string GenerateUpdateCommand(System.Data.DataTable aTable, string aCommandText)
{
try
{
StringBuilder whereClauseBuilder = new StringBuilder();
foreach (System.Data.DataColumn key in aTable.PrimaryKey)
{
if (whereClauseBuilder.Length > 0)
whereClauseBuilder.Append(" AND ");
whereClauseBuilder.Append(string.Format(" [{0}] = @Original_{0}", key.ColumnName));
}

if (whereClauseBuilder.Length == 0)
return aCommandText;

int position = aCommandText.IndexOf("WHERE") + 5;
return aCommandText.Substring(0, position) + whereClauseBuilder.ToString();
}
catch
{
return aCommandText;
}
}

/// <summary>
/// DbDataAdapter 保存 DataTable
/// </summary>
/// <param name="aDataSet">DataSet</param>
/// <returns>影响行数</returns>
public int SaveDataSet(System.Data.DataSet aDataSet)
{
System.Data.Common.DbTransaction trans = null;
try
{
using (System.Data.Common.DbConnection connection = CreateConnection())
{
connection.Open();

trans = connection.BeginTransaction();
int updates = 0;
foreach (System.Data.DataTable item in aDataSet.Tables)
{
updates += SaveTable(item);
}
trans.Commit();
return updates;
}
}
catch
{
trans.Rollback();
throw;
}
}

/// <summary>
/// DbDataAdapter 保存 DataTable
/// </summary>
/// <param name="aDataTable">DataTable</param>
/// <param name="aTransaction">DbTransaction</param>
/// <returns>影响行数</returns>
int SaveTable(System.Data.DataTable aDataTable)
{
return SaveDataTable(aDataTable,aDataTable.TableName);
}

#endregion

/// <summary>
/// 虚函数,子类生成DbDataAdapter
/// </summary>
/// <returns>DbDataAdapter</returns>
public virtual System.Data.Common.DbDataAdapter CreateAdapter()
{
return null;
}

/// <summary>
/// 虚函数,子类生成DbCommandBuilder
/// </summary>
/// <returns>DbCommandBuilder</returns>
public virtual System.Data.Common.DbCommandBuilder CreateCommandBuilder()
{
return null;
}

/// <summary>
/// 虚函数,子类生成DbCommandBuilder
/// </summary>
/// <returns>DbCommandBuilder</returns>
public virtual System.Data.Common.DbConnection CreateConnection()
{
return null;
}
}

以上定义数据访问基类,实现ado.net的数据访问讲很简单

认真看的同学可能发现里面更新table的时候使用了按主键更新的功能,还有就是乱抛错误,把sql也包含在错误信息中,在实际应用中可能要做调整的


    /// <summary>
/// Sql server 访问基类
/// </summary>
public class SQLAccess : DataAccess
{
/// <summary>
/// New
/// </summary>
public SQLAccess()
{

}

/// <summary>
/// New
/// </summary>
/// <param name="aConnectionString">connectionString</param>
public SQLAccess(string aConnectionString)
{
cnnstr = aConnectionString;
}

/// <summary>
/// 实现基类方法
/// </summary>
/// <returns>DbDataAdapter</returns>
public override System.Data.Common.DbDataAdapter CreateAdapter()
{
return new System.Data.SqlClient.SqlDataAdapter();
}

/// <summary>
/// 实现基类方法
/// </summary>
/// <returns>DbDataAdapter</returns>
public override System.Data.Common.DbConnection CreateConnection()
{
if (string.IsNullOrEmpty(cnnstr))
{
object RemotingConnectKey = System.Runtime.Remoting.Messaging.CallContext.GetData("RemotingConnectKey");
if (RemotingConnectKey != null)
cnnstr = System.Configuration.ConfigurationManager.AppSettings[RemotingConnectKey.ToString()];

if (string.IsNullOrEmpty(cnnstr))
cnnstr = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
}

return new System.Data.SqlClient.SqlConnection(cnnstr);
}

/// <summary>
/// 实现基类方法
/// </summary>
/// <returns>DbCommandBuilder</returns>
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
{
return new System.Data.SqlClient.SqlCommandBuilder();
}

}

DataAccess SqlHelper

时间: 2024-10-09 07:27:17

DataAccess SqlHelper的相关文章

.net C# SqlHelper for Oracle

适用于Oracle的sqlhelper 需要使用ODP.Net,引用Oracle.DataAccess.dll 推荐安装ODAC 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Data; using System.Config

【2016-11-2】【坚持学习】【Day17】【微软 推出的SQLHelper】

从网络上找到 微软原版本的SQLHelper,很多行代码.认真看了,学习了. 代码: 1 using System; 2 using System.Data; 3 using System.Xml; 4 using System.Data.SqlClient; 5 using System.Collections; 6 7 namespace Helper 8 { 9 /// <summary> 10 /// The SqlHelper class is intended to encapsu

对SqlHelper的理解

简介 Sqlhelper 是用来避免重复输入连接数据库代码的类,封装后只需要给类中的方法传入一些参数如数据库连接字符串,SQL参数等就可以访问数据库了.因为我们要声明该类不能被继承或实例化,所以我们要通过静态方法来封装数据访问功能.静态方法为类所有,可以通过对象来使用,也可以通过类来使用.但一般提倡通过类名来使用,应为静态方法只要定义了类,不必建立类的实例就可使用. 机制 上面说了SqlHelper的简介,接下来介绍它具体的运行机制.首先和普通连接数据库的步骤一样,要先定义Connection对

机房收费系统中sqlhelper的应用

在接受了三层的思想之后,sqlhelper被传的沸沸扬扬,它给我们的编码带来多少优势.让编码者少花了多少时间.多少精力,等等的赞美之词不绝于耳.自己也是将信将疑的,毕竟自己没有亲身经历,所以没有很大的体会.而如今,自己多次使用了sqlhelper,穿梭在各层之间确实也体会到了它带给我们的简便之处,结合很多人的版本自己编写了属于自己的那一版,以下便是具体代码: <span style="font-family:KaiTi_GB2312;font-size:18px;">Imp

公共的数据库访问访问类 SqlHelper.cs

/// <summary> /// 类说明:公共的数据库访问访问类 /// </summary> using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Collections; namespace DotNet.Utilities { /// <summary> /// 

DapperHelper,SqlHelper

using System;using System.Collections.Generic;using System.Data.Common;using System.Linq;using System.Text;using System.Threading.Tasks;using Dapper;using System.Configuration;using System.Data.SqlClient;using System.Data; namespace OADemo.Tool{ publ

SqlHelper中IN集合场景下的参数处理

我手头有个古老的项目,持久层用的是古老的ADO.net.前两天去昆明旅游,其中的一个景点是云南民族村,通过导游介绍知道了一个古老的民族——基诺族,这是我国的第56个民族.  项目里的ado.net和基诺族一样古老. 话说,项目里数据访问层,好多都是拼的sql,这给sql注入提供了可乘之机,为了系统安全,决定在有限的时间内,将它改成参数化. 其中,有个根据多个订单号查询支付单的方法,签名如下: public DataTable GetAlipayNotifyRecords(AlipayPaymen

C#实现较为实用的SQLhelper

第一次写博客,想不到写什么好b( ̄▽ ̄)d ,考虑的半天决定从sqlhelper开始,sqlhelper对程序员来说就像helloworld一样,很简单却又很重要,helloworld代表着程序员萌新第一次写代码,而sqlhelper则是初次接触数据库(不知道这种说法对不对). 好了不废话了,下面直接上代码(无话可说了): 1 public class SQLHelper 2 { 3 // 超时时间 4 private static int Timeout = 1000; 5 // 数据库名称

微软原版SQLHelper类

C# Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84