DBHelper数据库操作类(一)

本文涉及的产品
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
云数据库 RDS SQL Server,基础系列 2核4GB
简介: 个人分享地址: 可以参考的:http://www.oschina.net/code/snippet_4946_748                  http://www.oschina.net/code/snippet_172400_8847   using System;using System.

个人分享地址:

可以参考的:http://www.oschina.net/code/snippet_4946_748

                 http://www.oschina.net/code/snippet_172400_8847

 

using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Data.OracleClient;
using System.Data.Odbc;
using System.Data.Common;
//using DICOM;
namespace SPD.ERP.DBAccess
{
  /// <summary>
    /// 数据库的类型
    /// </summary>
    public enum DatabaseType
    {
        None,
        SQLServer,
        Oracle,
        ODBC,
    }
   
    public sealed class DbFactory
    {
        private static string connectionString;
        private static DatabaseType dbType = DatabaseType.SQLServer;
        public static string GetConnectString
        {
            get
            {
                if (string.IsNullOrEmpty(connectionString))
                {
                    connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["db1"].ConnectionString;
                   
                }
                return connectionString;
            }
        }

        /// <summary>
        /// 执行查询语句
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static DataSet DoQuery(DbConnection conn, DbTransaction trans, string strSql)
        {
            DbDataAdapter dAdapter = DbFactory.CreateAdapter(strSql, conn);
            try
            {
                dAdapter.SelectCommand.Transaction = trans;
                DataSet ds = new DataSet();
                dAdapter.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
               throw e;
            }
            finally
            {
                dAdapter.Dispose();
            }


        }
        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <param name="conn"></param>
        public static void CloseConnection(DbConnection conn)
        {
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Dispose();
        }

        /// <summary>
        /// 创建连接
        /// </summary>
        public static DbConnection CreateConnection
        {
            get
            {
                DbConnection conn = null;
                try
                {
                    switch (dbType)
                    {
                        case DatabaseType.SQLServer:
                            conn = new SqlConnection(GetConnectString);
                            break;
                        case DatabaseType.Oracle:
                            conn = new OracleConnection(GetConnectString);
                            break;
                        case DatabaseType.ODBC:
                            conn = new OdbcConnection(GetConnectString);
                            break;
                        default:  //
                            conn = new OleDbConnection(GetConnectString);
                            break;
                    }
                    if (conn != null)
                    {
                        try
                        {
                            conn.Open();
                        }
                        catch (Exception e)
                        {
                            throw e;
                        }
                        return conn;
                    }
                    else
                        throw new Exception("创建连接失败!");
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="dbtype"></param>
        /// <returns></returns>
        public static DbDataAdapter CreateAdapter(DbCommand cmd, DatabaseType dbtype)
        {
            DbDataAdapter da = null;
            switch (dbtype)
            {
                case DatabaseType.SQLServer:
                    da = new SqlDataAdapter((SqlCommand)cmd);
                    break;
                case DatabaseType.Oracle:
                    da = new OracleDataAdapter((OracleCommand)cmd);
                    break;
                case DatabaseType.ODBC:
                    da = new OdbcDataAdapter((OdbcCommand)cmd);
                    break;
                default:    //其它的用OLEDB
                    da = new OleDbDataAdapter((OleDbCommand)cmd);
                    break;
            }

            return da;
        }


        /// <summary>
        ///
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static DbDataAdapter CreateAdapter(DbCommand cmd)
        {
            DbDataAdapter da = null;
            switch (dbType)
            {
                case DatabaseType.SQLServer:
                    da = new SqlDataAdapter((SqlCommand)cmd);
                    break;
                case DatabaseType.Oracle:
                    da = new OracleDataAdapter((OracleCommand)cmd);
                    break;
                case DatabaseType.ODBC:
                    da = new OdbcDataAdapter((OdbcCommand)cmd);
                    break;
                default:    //
                    da = new OleDbDataAdapter((OleDbCommand)cmd);
                    break;
            }
            return da;
        }

 

        /// <summary>
        /// 数据适配器
        /// </summary>
        /// <param name="selectComandText"></param>
        /// <param name="cnn"></param>
        /// <returns></returns>
        public static DbDataAdapter CreateAdapter(string selectComandText, DbConnection cnn)
        {
            DbDataAdapter da = null;
            switch (dbType)
            {
                case DatabaseType.SQLServer:
                    da = new SqlDataAdapter(selectComandText, (SqlConnection)cnn);
                    break;

                case DatabaseType.Oracle:
                    da = new OracleDataAdapter(selectComandText, (OracleConnection)cnn);
                    break;
                case DatabaseType.ODBC:
                    da = new OdbcDataAdapter(selectComandText, (OdbcConnection)cnn);
                    break;
                default:    //
                    da = new OleDbDataAdapter(selectComandText, (OleDbConnection)cnn);
                    break;
            }

            return da;

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="CommandText"></param>
        /// <param name="dbtype"></param>
        /// <param name="cnn"></param>
        /// <returns></returns>

        public static DbCommand CreateCommand(string commandText, DatabaseType dbtype, DbConnection cnn)
        {
            DbCommand cmd = null;
            switch (dbtype)
            {
                case DatabaseType.SQLServer:
                    cmd = new SqlCommand(commandText, (SqlConnection)cnn);
                    break;

                case DatabaseType.Oracle:
                    cmd = new OracleCommand(commandText, (OracleConnection)cnn);
                    break;
                case DatabaseType.ODBC:
                    cmd = new OdbcCommand(commandText, (OdbcConnection)cnn);
                    break;
                default:   //
                    cmd = new OleDbCommand(commandText, (OleDbConnection)cnn);
                    break;
            }

            return cmd;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="CommandText"></param>
        /// <param name="cnn"></param>
        /// <returns></returns>
        public static DbCommand CreateCommand(string commandText, DbConnection cnn)
        {
            DbCommand cmd = null;
            switch (dbType)
            {
                case DatabaseType.SQLServer:
                    cmd = new SqlCommand(commandText, (SqlConnection)cnn);
                    break;

                case DatabaseType.Oracle:
                    cmd = new OracleCommand(commandText, (OracleConnection)cnn);
                    break;
                case DatabaseType.ODBC:
                    cmd = new OdbcCommand(commandText, (OdbcConnection)cnn);
                    break;
                default:   //
                    cmd = new OleDbCommand(commandText, (OleDbConnection)cnn);
                    break;
            }

            return cmd;
        }

        public static DbCommand CreateCommand(string commandText, DbConnection cnn, DbTransaction trans)
        {
            DbCommand cmd = null;
            switch (dbType)
            {
                case DatabaseType.SQLServer:
                    cmd = new SqlCommand(commandText, (SqlConnection)cnn, (SqlTransaction)trans);
                    break;

                case DatabaseType.Oracle:
                    cmd = new OracleCommand(commandText, (OracleConnection)cnn, (OracleTransaction)trans);
                    break;
                case DatabaseType.ODBC:
                    cmd = new OdbcCommand(commandText, (OdbcConnection)cnn, (OdbcTransaction)trans);
                    break;
                default:   //
                    cmd = new OleDbCommand(commandText, (OleDbConnection)cnn, (OleDbTransaction)trans);
                    break;
            }

            return cmd;
        }


        public static DbCommandBuilder CreateCommandBuilder()
        {
            DbCommandBuilder cmb = null;
            switch (dbType)
            {
                case DatabaseType.SQLServer:
                    cmb = new SqlCommandBuilder();
                    break;

                case DatabaseType.Oracle:
                    cmb = new OracleCommandBuilder();
                    break;
                case DatabaseType.ODBC:
                    cmb = new OdbcCommandBuilder();
                    break;
                default:   //
                    cmb = new OleDbCommandBuilder();
                    break;
            }

            return cmb;
        }


        public static DbCommandBuilder CreateCommandBuilder(DbDataAdapter dat)
        {
            DbCommandBuilder cmb = null;
            switch (dbType)
            {
                case DatabaseType.SQLServer:
                    cmb = new SqlCommandBuilder((SqlDataAdapter)dat);
                    break;

                case DatabaseType.Oracle:
                    cmb = new OracleCommandBuilder((OracleDataAdapter)dat);
                    break;
                case DatabaseType.ODBC:
                    cmb = new OdbcCommandBuilder((OdbcDataAdapter)dat);
                    break;
                default:   //
                    cmb = new OleDbCommandBuilder((OleDbDataAdapter)dat);
                    break;
            }

            return cmb;
        }

        /// <summary>
        /// 执行查询语句
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static DataSet DoQuery(string strSql)
        {

            DbConnection conn = DbFactory.CreateConnection;
            DbDataAdapter dAdapter = DbFactory.CreateAdapter(strSql, conn);
            try
            {
                DataSet ds = new DataSet();
                dAdapter.SelectCommand.CommandTimeout = 0;
                dAdapter.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
               throw e;
            }
            finally
            {
                dAdapter.Dispose();
                DbFactory.CloseConnection(conn);
            }

        }

        public static DataSet GetDataSchema(string strSql)
        {
            DbConnection conn = DbFactory.CreateConnection;
            try
            {
                using (DbDataAdapter dAdapter = DbFactory.CreateAdapter(strSql, conn))
                {
                    DataSet ds = new DataSet();
                    dAdapter.FillSchema(ds, SchemaType.Mapped);
                    return ds;
                }
            }
            catch (Exception e)
            {
               throw e;
            }
            finally
            {
                DbFactory.CloseConnection(conn);
            }
        }

        /// <summary>
        /// 执行查询语句
        /// </summary>
        /// <param name="strSql">查询语句</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public static DataSet DoQuery(string strSql, string tableName)
        {

            DbConnection conn = DbFactory.CreateConnection;
            try
            {
                using (DbDataAdapter dAdapter = DbFactory.CreateAdapter(strSql, conn))
                {
                    DataSet ds = new DataSet();
                    dAdapter.SelectCommand.CommandTimeout = 0;
                    //dAdapter.Fill(ds);
                    dAdapter.FillSchema(ds, SchemaType.Mapped, tableName);
                    dAdapter.Fill(ds, tableName);
                    ds.Tables[0].TableName = tableName;
                    //Utils.Tools.RemoveDataTablePrimaryAndAllowDBNull(ds);
                    return ds;
                }


            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DbFactory.CloseConnection(conn);
            }

        }

        /// <summary>
        /// 执行查询语句
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static DataSet DoQuery(DbConnection conn, string strSql)
        {
            DbDataAdapter dAdapter = DbFactory.CreateAdapter(strSql, conn);
            try
            {
                dAdapter.SelectCommand.CommandTimeout = 0;
                DataSet ds = new DataSet();
                dAdapter.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
               throw e;
            }
            finally
            {
                dAdapter.Dispose();
            }


        }


        /// <summary>
        /// 执行返回单一变量的sql
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static object DoQueryResultSingleValue(string strSql)
        {
            DbConnection conn = DbFactory.CreateConnection;
            using (DbCommand dc = DbFactory.CreateCommand(strSql, conn))
            {
                dc.CommandTimeout = 0;
                DbDataReader dr = dc.ExecuteReader();
                object obj = null;
                while (dr.Read())
                {
                    obj = dr.GetValue(0);
                    break;
                }
                dr.Close();
                DbFactory.CloseConnection(conn);
                return obj;
            }
        }

        /// <summary>
        /// 执行返回单一变量的sql
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static object DoQueryResultSingleValue(DbConnection conn, string strSql)
        {
            using (DbCommand dc = DbFactory.CreateCommand(strSql, conn))
            {
                dc.CommandTimeout = 0;
                object obj = null;
                using (DbDataReader dr = dc.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        obj = dr.GetValue(0);
                        break;
                    }

                    dr.Close();
                }
                return obj;
            }
        }

        /// <summary>
        /// 执行返回单一变量的sql
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static object DoQueryResultSingleValue(DbConnection conn, DbTransaction tran, string strSql)
        {
            using (DbCommand dc = DbFactory.CreateCommand(strSql, conn, tran))
            {
                object obj = null;
                dc.CommandTimeout = 0;
                using (DbDataReader dr = dc.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        obj = dr.GetValue(0);
                        break;
                    }

                    dr.Close();
                }
                return obj;
            }
        }


        /// <summary>
        /// 执行没有返回结果集的Sql
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string strSql)
        {
            DbConnection conn = DbFactory.CreateConnection;
            using (DbCommand dc = DbFactory.CreateCommand(strSql, conn))
            {
                dc.CommandTimeout = 0;
                try
                {
                    return dc.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    DbFactory.CloseConnection(conn);
                }
            }
        }

        /// <summary>
        /// 执行返回DbDataReader结果集的sql
        /// </summary>
        /// <param name="conn">数据连接对象</param>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static DbDataReader ExecuteReader(DbConnection conn, string strSql)
        {
            using (DbCommand dc = DbFactory.CreateCommand(strSql, conn))
            {
                dc.CommandTimeout = 0;
                DbDataReader dr = dc.ExecuteReader();
                return dr;
            }
        }

        /// <summary>
        /// 执行返回DbDataReader结果集的sql
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static DbDataReader ExecuteReader(DbConnection conn, DbTransaction tran, string strSql)
        {
            using (DbCommand dc = DbFactory.CreateCommand(strSql, conn))
            {
                dc.CommandTimeout = 0;
                dc.Transaction = tran;
                DbDataReader dr = dc.ExecuteReader();
                return dr;
            }
        }

 

        /// <summary>
        /// 执行没有返回结果集的Sql,需要事务支持
        /// </summary>
        /// <param name="conn">连接对象</param>
        /// <param name="tran">事务对象</param>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public static int ExecuteNonQuery(DbConnection conn, IDbTransaction tran, string strSql)
        {
            using (IDbCommand dc = DbFactory.CreateCommand(strSql, conn))
            {
                dc.CommandTimeout = 0;
                dc.Transaction = tran;
                try
                {
                    return dc.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                   throw e;
                }
            }

        }


        /// <summary>
        /// 设置DBDataAdapter的sql
        /// </summary>
        /// <param name="adapter"></param>
        public static void SetDbDataAdapterCommand(DbDataAdapter adapter)
        {

            DbCommandBuilder cb = CreateCommandBuilder(adapter);
            adapter.UpdateCommand = cb.GetUpdateCommand();
            adapter.InsertCommand = cb.GetInsertCommand();
            adapter.DeleteCommand = cb.GetDeleteCommand();


        }


        /// <summary>
        /// 设置DbDataAdapter的事务
        /// </summary>
        /// <param name="adapter"></param>
        /// <param name="tran"></param>
        public static void SetDbDataAdapterTransaction(DbDataAdapter adapter, DbTransaction tran)
        {
            adapter.DeleteCommand.Transaction = tran;
            adapter.SelectCommand.Transaction = tran;
            adapter.UpdateCommand.Transaction = tran;
            adapter.InsertCommand.Transaction = tran;

        }

        /// <summary>
        /// 保存数据集
        /// </summary>
        /// <param name="dsSource">数据源  (数据源中的表名必须是实际的数据表名)</param>
        /// <param name="conn">数据连接对象</param>
        /// <param name="tran">事物对象</param>
        public static void UpdateDateSet(DataSet dsSource, DbConnection conn, DbTransaction tran)
        {
            if (dsSource == null || conn == null || tran == null) return;
            if (dsSource.Tables.Count == 0) return;
            try
            {
                foreach (DataTable dtSource in dsSource.Tables)
                {
                    UpdateDataTable(dtSource, conn, tran);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 保持数据表
        /// </summary>
        /// <param name="dtSource">数据源  (数据源中的表名必须是实际的数据表名)</param>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        public static void UpdateDataTable(DataTable dtSource, DbConnection conn, DbTransaction tran)
        {
            if (dtSource == null || conn == null || tran == null) return;
            try
            {
                string sqlCmd = string.Format("SELECT * FROM [{0}]", dtSource.TableName);
                DbCommand dbCommand = CreateCommand(sqlCmd, conn, tran);
                DbDataAdapter adapter = CreateAdapter(dbCommand);
                DbCommandBuilder cmdBuilder = CreateCommandBuilder(adapter);
                adapter.DeleteCommand = cmdBuilder.GetDeleteCommand();
                adapter.InsertCommand = cmdBuilder.GetInsertCommand();
                adapter.UpdateCommand = cmdBuilder.GetUpdateCommand();
                adapter.Update(dtSource);
            }
            catch (Exception e)
            {
                throw e;
            }


        }
    }


}

 

 

目录
相关文章
|
Java 数据库连接 数据库
JDBC学习(三):封装工具类JDBCUtils类
为了以后方便进行数据库连接、数据库关闭、还有后面的连接池的操作等功能,现在将功能封装到JDBCUtils类当中,作为自己的一个工具箱。
394 0
|
6月前
|
NoSQL 关系型数据库 MySQL
数据库操作( CURD )
数据库操作( CURD )
36 5
|
存储 Java 数据库连接
MyBatis 调用存储过程
MyBatis 调用存储过程
80 0
|
SQL 数据库
编写SQLHelper类
编写SQLHelper类
84 1
|
存储 SQL XML
Mybatis-9-调用存储过程
存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集。经编译后存储在数据库中。现在要使用Mybatis调用数据库的存储过程。
118 0
Mybatis-9-调用存储过程
|
SQL 网络安全 PHP
封装数据库操作类(构造方法)|学习笔记
快速学习封装数据库操作类(构造方法)
|
SQL 存储 数据库
C#之数据库操作类
  平时在进行C#开发时,需要对数据库进行操作,下面介绍几种常见的操作数据库的方法:   一、操作类DataAccess   using System;   using System.Collections.Generic;   using System.Linq;   using System.Text;   using System.Data;   using System.Data.SqlClient;   using DevExpress.XtraEditors;   using System.Windows.Forms;   //自己写的解密数据库链接dll,可
454 0
|
SQL Java 数据库连接
MyBatis超详细介绍——SQL语句构建器类
MyBatis超详细介绍——SQL语句构建器类 (本文作为学习笔记,了解更多请参考:MyBatis参考文档) MyBatis3提供了SQL类帮助构造SQL语句: private String selectPersonSql() { return new SQL() {{ SELECT("P.
2784 0
|
存储 Java 数据库连接