DataAccess SqlHelper
时间:2014-05-19 08:59:56
收藏:0
阅读:454
/// <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(); } }
评论(0)