using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
using System.Collections;
using System.Reflection;
using System.Collections.Specialized;
using System.Configuration;
using System.ComponentModel;
using System.IO;
using System.Text.RegularExpressions;
using CP.Utility; namespace CP.DBService
{
public class DBHelper
{
protected string ConnectionString { get; set; }
protected DataBaseType DBType { get; set; }
private static DBHelper helper;
private static bool hasRead = false;
private static DBHelper gpmHelper;
protected DBHelper() { }
/// <summary>
/// 创建单例模式
/// </summary>
/// <param name="connectionString"></param>
/// <param name="dbType"></param>
/// <returns></returns>
public static DBHelper CreateInstance()
{
if (helper == null)
{
helper = new DBHelper();
helper.ConnectionString = EncryptHelper.DecryptDES(ConfigurationManager.ConnectionStrings["BizConnectionString"].ConnectionString, "masicsyc");
//helper.ConnectionString = ConfigurationManager.ConnectionStrings["BizConnectionString"].ConnectionString;
helper.DBType = DataBaseType.Oracle;
}
return helper;
} public static DBHelper GPMCreateInstance()
{
if (gpmHelper == null)
{
gpmHelper = new DBHelper();
gpmHelper.ConnectionString = EncryptHelper.DecryptDES(ConfigurationManager.ConnectionStrings["GPMConnectionString"].ConnectionString, "masicgpm");
//helper.ConnectionString = ConfigurationManager.ConnectionStrings["GPMConnectionString"].ConnectionString;
gpmHelper.DBType = DataBaseType.Oracle;
}
return gpmHelper;
} public static DBHelper CreateNonSingleTonInstance()
{
helper = new DBHelper();
helper.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
helper.DBType = DataBaseType.Oracle;
return helper; } DbTransaction transaction = null;
public DbTransaction Transaction
{
get { return transaction; }
set { transaction = value; }
}
public void Commit()
{
Transaction.Commit();
Transaction = null;
GC.Collect();
}
public void Rollback()
{
Transaction.Rollback();
Transaction = null;
GC.Collect();
}
public virtual void BeginTransaction()
{
DbConnection transConnection = CreateConnection();
DbTransaction transaction = transConnection.BeginTransaction();
Transaction = transaction;
}
public virtual void CloseConnection(DbConnection connection)
{
if (Transaction == null)
connection.Close();
}
/// <summary>
/// 创建连接
/// </summary>
/// <returns></returns>
protected DbConnection CreateConnection()
{
if (Transaction != null) return Transaction.Connection;
DbConnection connection = null;
switch (DBType)
{
case DataBaseType.Access:
connection = new System.Data.OleDb.OleDbConnection(ConnectionString);
break;
case DataBaseType.MySql:
connection = new System.Data.OleDb.OleDbConnection(ConnectionString);
break;
case DataBaseType.Oracle:
connection = new System.Data.OracleClient.OracleConnection(ConnectionString);
break;
case DataBaseType.SqlServer:
connection = new System.Data.SqlClient.SqlConnection(ConnectionString);
break;
}
connection.Open();
return connection;
}
public DbCommand CreateCommand()
{
DbCommand command = CreateConnection().CreateCommand();
command.Transaction = Transaction;
return command;
}
/// <summary>
/// 创建命令
/// </summary>
/// <param name="connection"></param>
/// <param name="sqlSegment"></param>
/// <param name="parameters"></param>
/// <returns></returns>
protected DbCommand CreateCommand(DbConnection connection, string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{
DbCommand command = connection.CreateCommand();
command.CommandText = sqlSegment;
command.CommandType = commandType;
if (parameters != null)
command.Parameters.AddRange(parameters);
command.Transaction = Transaction;
return command;
}
/// <summary>
/// 创建适配器
/// </summary>
/// <param name="connection"></param>
/// <param name="sqlSegment"></param>
/// <param name="parameters"></param>
/// <returns></returns>
protected DbDataAdapter CreateAdapter(DbConnection connection, string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{
DbCommand command = CreateCommand(connection, sqlSegment, parameters, commandType);
command.CommandText = sqlSegment;
//command.CommandType = commandType;
//if (parameters != null)
// command.Parameters.AddRange(parameters); DbDataAdapter adapter = null;
switch (DBType)
{
case DataBaseType.Access:
adapter = new System.Data.OleDb.OleDbDataAdapter((System.Data.OleDb.OleDbCommand)command);
break;
case DataBaseType.MySql:
adapter = new System.Data.OleDb.OleDbDataAdapter((System.Data.OleDb.OleDbCommand)command);
break;
case DataBaseType.Oracle:
adapter = new System.Data.OracleClient.OracleDataAdapter((System.Data.OracleClient.OracleCommand)command);
break;
case DataBaseType.SqlServer:
adapter = new System.Data.SqlClient.SqlDataAdapter((System.Data.SqlClient.SqlCommand)command);
break;
}
return adapter;
} public virtual T ExecuteScalar<T>(string sqlSegment)
{
return ExecuteScalar<T>(sqlSegment, null);
}
public virtual T ExecuteScalar<T>(string sqlSegment, IDataParameter[] parameters)
{
return ExecuteScalar<T>(sqlSegment, null, CommandType.Text);
}
public virtual T ExecuteScalar<T>(string sqlSegment, CommandType commandType)
{
return ExecuteScalar<T>(sqlSegment, null, commandType);
}
public virtual T ExecuteScalar<T>(string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{
T result = default(T);
object value = ExecuteScalar(sqlSegment, parameters, commandType); if (value != null && value != DBNull.Value)
{
result = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString());
}
return result;
} public virtual object ExecuteScalar(string sqlSegment)
{
return ExecuteScalar(sqlSegment, null);
}
public virtual object ExecuteScalar(string sqlSegment, IDataParameter[] parameters)
{
return ExecuteScalar(sqlSegment, null, CommandType.Text);
}
public virtual object ExecuteScalar(string sqlSegment, CommandType commandType)
{
return ExecuteScalar(sqlSegment, null, commandType);
}
public virtual object ExecuteScalar(string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{
DbConnection connection = CreateConnection();
DbCommand command = CreateCommand(connection, sqlSegment, parameters, commandType); object result = command.ExecuteScalar();
command.Parameters.Clear();
CloseConnection(connection);
return result;
} /// <summary>
/// 执行SQL语句,返回影响的记录数,用于增/删/改数据
/// </summary>
/// <param name="sqlSegment"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public virtual int ExecuteNonQuery(string sqlSegment)
{
return ExecuteNonQuery(sqlSegment, null, CommandType.Text);
}
public virtual int ExecuteNonQuery(string sqlSegment, IDataParameter[] parameters)
{
return ExecuteNonQuery(sqlSegment, null, CommandType.Text);
}
public virtual int ExecuteNonQuery(string sqlSegment, CommandType commandType)
{
return ExecuteNonQuery(sqlSegment, null, commandType);
}
public virtual int ExecuteNonQuery(string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{
DbConnection connection = CreateConnection();
DbCommand command = CreateCommand(connection, sqlSegment, parameters, commandType);
int result = command.ExecuteNonQuery();
command.Parameters.Clear();
CloseConnection(connection);
return result;
} /// <summary>
/// 执行SQL语句,返回一张表,用于查询数据
/// </summary>
/// <param name="sqlSegment"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public virtual DataTable ExecuteDataTable(string sqlSegment)
{
return ExecuteDataTable(sqlSegment, null);
}
public virtual DataTable ExecuteDataTable(string sqlSegment, IDataParameter[] parameters)
{
return ExecuteDataTable(sqlSegment, null, CommandType.Text);
}
public virtual DataTable ExecuteDataTable(string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{ DataTable dataTable = new DataTable();
DbConnection connection = CreateConnection();
DbDataAdapter adapter = CreateAdapter(connection, sqlSegment, parameters, commandType);
adapter.Fill(dataTable);
adapter.SelectCommand.Parameters.Clear();
CloseConnection(connection);
return dataTable; } /// <summary>
/// 执行SQL语句,返回一个Reader对象,用于查询数据
/// </summary>
/// <param name="sqlSegment"></param>
/// <param name="parameters"></param>
/// <returns></returns>
//public virtual DbDataReader ExecuteReader(string sqlSegment)
//{
// return ExecuteReader(sqlSegment, null);
//}
//public virtual DbDataReader ExecuteReader(string sqlSegment, IDataParameter[] parameters)
//{
// return ExecuteReader(sqlSegment, null,CommandType.Text);
//}
//public virtual DbDataReader ExecuteReader(string sqlSegment, IDataParameter[] parameters,CommandType commandType)
//{
// DbConnection connection = CreateConnection();
// DbCommand command = CreateCommand(connection, sqlSegment, parameters,commandType);
// DbDataReader reader = command.ExecuteReader();
// return reader;
//} public virtual IList<T> ExecuteObject<T>(string sqlSegment)
{
return ExecuteObject<T>(sqlSegment, null);
}
public virtual IList<T> ExecuteObject<T>(string sqlSegment, IDataParameter[] parameters)
{
return ExecuteObject<T>(sqlSegment, parameters, CommandType.Text);
}
public virtual IList<T> ExecuteObject<T>(string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{
return ExecuteObject<T>(sqlSegment, parameters, commandType, null);
}
public virtual IList<T> ExecuteObject<T>(string sqlSegment, IDataParameter[] parameters, CommandType commandType, string entity_type)
{
DbConnection connection = CreateConnection();
DbCommand command = CreateCommand(connection, sqlSegment, parameters, commandType); IList<T> entities = new List<T>();
try
{
using (DbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
T entity = Activator.CreateInstance<T>();
if (!string.IsNullOrEmpty(entity_type))
{
entity = (T)PortalService.CreateEntity(entity_type);
} var properties = entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
object value = reader[property.Name];
object new_value = null;
if (value == null || value == DBNull.Value)
{
if (property.PropertyType == typeof(int) ||
property.PropertyType == typeof(Int32))
new_value = ;
if (property.PropertyType == typeof(decimal))
new_value = 0m;
if (property.PropertyType == typeof(float))
new_value = 0f;
if (property.PropertyType == typeof(double))
new_value = 0d;
if (property.PropertyType == typeof(bool))
new_value = false;
if (property.PropertyType == typeof(DateTime))
new_value = DateTime.MinValue;
}
else
{
if (property.PropertyType == value.GetType())
new_value = value;
else if (property.PropertyType == typeof(DateTime?))
new_value = value;
else if (property.PropertyType == typeof(bool))
new_value = value.ToString() == "" ? false : true;
else if (property.PropertyType == typeof(byte[]))
new_value = (byte[])value;
else
new_value = TypeDescriptor.GetConverter(property.PropertyType).ConvertFrom(value.ToString()); //if (new_value != null)
//{
// //if (new_value.GetType() == typeof(string) && new_value.ToString() == " ")
// // new_value = "";
// if (new_value.GetType() == typeof(decimal) && (decimal)new_value != 0m && new_value.ToString().IndexOf(".") > 0)
// {
// string str_new_value = new_value.ToString();
// str_new_value = Regex.Replace(str_new_value, "0+$", "");
// new_value = decimal.Parse(str_new_value);
// }
//}
} property.SetValue(entity, new_value, null);
}
entities.Add(entity);
}
reader.Close(); }
}
catch (Exception ex)
{
throw new Exception("执行SQL语句发生错误:" + sqlSegment + ".详细描述" + ex.Message, ex);
}
finally
{
CloseConnection(connection);
}
command.Parameters.Clear();
return entities; } public virtual T ExecuteSingleObject<T>(string sqlSegment)
{
return ExecuteSingleObject<T>(sqlSegment, null);
}
public virtual T ExecuteSingleObject<T>(string sqlSegment, IDataParameter[] parameters)
{
return ExecuteSingleObject<T>(sqlSegment, parameters, CommandType.Text);
}
public virtual T ExecuteSingleObject<T>(string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{
return ExecuteSingleObject<T>(sqlSegment, parameters, commandType, null);
}
public virtual T ExecuteSingleObject<T>(string sqlSegment, IDataParameter[] parameters, CommandType commandType, string entity_type)
{
DbConnection connection = CreateConnection();
DbCommand command = CreateCommand(connection, sqlSegment, parameters, commandType); T entity = Activator.CreateInstance<T>();
try
{
using (DbDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
if (!string.IsNullOrEmpty(entity_type))
{
entity = (T)PortalService.CreateEntity(entity_type);
} var properties = entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
object value = reader[property.Name];
object new_value = null;
if (value == DBNull.Value)
{
if (property.PropertyType == typeof(int) ||
property.PropertyType == typeof(Int32))
new_value = ;
if (property.PropertyType == typeof(decimal))
new_value = 0m;
if (property.PropertyType == typeof(float))
new_value = 0f;
if (property.PropertyType == typeof(double))
new_value = 0d;
if (property.PropertyType == typeof(bool))
new_value = false;
if (property.PropertyType == typeof(DateTime))
new_value = DateTime.MinValue;
}
else
{
if (property.PropertyType == value.GetType())
new_value = value;
else if (property.PropertyType == typeof(DateTime?))
new_value = value;
else if (property.PropertyType == typeof(bool))
new_value = value.ToString() == "" ? false : true;
else if (property.PropertyType == typeof(byte[]))
new_value = (byte[])value;
else
new_value = TypeDescriptor.GetConverter(property.PropertyType).ConvertFrom(value.ToString());
} property.SetValue(entity, new_value, null);
}
reader.Close();
}
}
}
catch (Exception ex)
{
throw new Exception("执行SQL语句发生错误:" + sqlSegment + ".详细描述" + ex.Message, ex);
}
finally
{
CloseConnection(connection);
}
command.Parameters.Clear();
return entity;
} public virtual IList<T> ExecuteSimpleTypeList<T>(string sqlSegment)
{
return ExecuteSimpleTypeList<T>(sqlSegment, null);
}
public virtual IList<T> ExecuteSimpleTypeList<T>(string sqlSegment, IDataParameter[] parameters)
{
return ExecuteSimpleTypeList<T>(sqlSegment, parameters, CommandType.Text);
}
public virtual IList<T> ExecuteSimpleTypeList<T>(string sqlSegment, IDataParameter[] parameters, CommandType commandType)
{
DbConnection connection = CreateConnection();
DbCommand command = CreateCommand(connection, sqlSegment, parameters, commandType); IList<T> entities = new List<T>();
try
{
using (DbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
T result = default(T);
object value = reader[];
if (value == null || value == DBNull.Value)
continue;
result = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString());
entities.Add(result);
}
reader.Close();
}
}
catch (Exception ex)
{
throw new Exception("执行SQL语句发生错误:" + sqlSegment + ".详细描述" + ex.Message, ex);
}
finally
{
CloseConnection(connection);
}
command.Parameters.Clear();
return entities;
} } public enum DataBaseType
{
Access,
SqlServer,
Oracle,
MySql
}
}
  

SqlHelper include Transaction的更多相关文章

  1. 微软版的SqlHelper.cs类

    一,微软SQLHelper.cs类 中文版: using System; using System.Data; using System.Xml; using System.Data.SqlClien ...

  2. SqlHelper类

    using System; using System.Collections; using System.Collections.Generic; using System.Data; using S ...

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

    从网络上找到 微软原版本的SQLHelper,很多行代码.认真看了,学习了.  代码:  using System; using System.Data; using System.Xml; usin ...

  4. SqlHelper c#

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  5. SQLHelper

    今天学习了.net后,经过老师的一番讲解,似乎对它越来越渴望了,希望自己在接下来的学习当中,能很好的驾驭.net,加油吧, 下面我分享一个操作SQL数据库的代码大全,谢谢观赏.嘿嘿,还是比较长的哦, ...

  6. C#版SQLHelper.cs类

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  7. 微软SQLHelper.cs类 中文版

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Co ...

  8. 万能的SQLHelper帮助类

    /// <summary> /// 数据库帮助类 /// </summary> public class SQLHelper { private static string c ...

  9. 微软原版SQLHelper类

    代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-- ...

随机推荐

  1. LINE最新版6.5.0在iOS上的删除信息取证

    iOS: 9.3.2版 LINE: 6.5.0版 取出LINE的数据库 Line.sqlite,路径如下所示: 检视删除的信息,发现还有不少残留,虽然都是片段,但拼拼凑凑总还是能有些蛛丝马迹,毕竟,总 ...

  2. leetcode 107

    107. Binary Tree Level Order Traversal II Given a binary tree, return the bottom-up level order trav ...

  3. Data Mover Script Templates

    Datamover is probably the best way to export and import data between PeopleSoft databases and the sc ...

  4. Knockout.Js官网学习(数组observable)

    前言 如果你要探测和响应一个对象的变化,你应该用observables. 如果你需要探测和响应一个集合对象的变化,你应该用observableArray . 在很多场景下,它都非常有用,比如你要在UI ...

  5. CSS计数器与动态计数呈现

    代码: CSS代码: body { counter-reset: icecream; } input:checked { counter-increment: icecream; } .total:: ...

  6. ip的正则表达式 完美版

    IP地址的长度为32位2进制,分为4段,每段8位,用十进制数字表示,每段数字范围为0~255,段与段之间用英文句点“.”隔开.例如:IP地址为10.0.0.100. 分析IP地址的每组数特点:百位,十 ...

  7. [转发]导出Excel 格式 mso-number-format

    应用中经常会遇到要从系统或数据库中导出数据平面文件,一般是导出到txt,csv或excel.txt和csv一般用在系统间的数据交换,而 excel一般有较好的显示效果,可以按照一定的模板导出,导出就不 ...

  8. Hive中典型的表内数据除重写法

    insert overwrite table store select t.p_key,t.sort_word from ( select p_key, sort_word , row_number( ...

  9. 【自己动手】sublime text插件开发

    今天是五四青年节,在此先祝大家节日快乐!!! --------------------------------------------华丽的分界线--------------------------- ...

  10. scala函数组合器

    1.map 在列表中的每个元素上计算一个函数,并且返回一个包含相同数目元素的列表. scala> numbers.map(_ * 2)res3: Array[Int] = Array(2, 4, ...