• C# 能连接4种数据库(外加文件操作)DatabaseHelp 类


    首先在工程中引用各种数据库组件.
    包括:SqlServer,OleDb,Oracle,ODBC.
    调用方法很简单,在创建该类的实例对象时初始化connectionstring数据库连接字符串即可.
    该类提供了几种初始化重载方法,可以直接将连接字符串传入,或者通过web.config配置文件ConnectionStrings["connectionstring"].可以直接指明数据库类型,也可以不指明(该类有自动分析功能).
     
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Data;
    using System.Configuration;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Data.OleDb;
    using System.Data.Odbc;
    using System.Data.OracleClient;
    using System.IO;
     
    /// <summary>
    /// DatebaseHelper 的摘要说明
    /// </summary>
    public class DatebaseHelper
    {
        public class DatabaseHelper : IDisposable
        {
            private string strConnectionString;
            private DbConnection objConnection;
            private DbCommand objCommand;
            private DbProviderFactory objFactory = null;
            private bool boolHandleErrors;
            private string strLastError;
            private bool boolLogError;
            private string strLogFile;
     
            public DatabaseHelper(string connectionstring, Providers provider)
            {
                strConnectionString = connectionstring;
                switch (provider)
                {
                    case Providers.SqlServer:
                        objFactory = SqlClientFactory.Instance;
                        break;
                    case Providers.OleDb:
                        objFactory = OleDbFactory.Instance;
                        break;
                    case Providers.Oracle:
                        objFactory = OracleClientFactory.Instance;
                        break;
                    case Providers.ODBC:
                        objFactory = OdbcFactory.Instance;
                        break;
                    case Providers.ConfigDefined:
                        string providername = ConfigurationManager.ConnectionStrings["connectionstring"].ProviderName;
                        switch (providername)
                        {
                            case "System.Data.SqlClient":
                                objFactory = SqlClientFactory.Instance;
                                break;
                            case "System.Data.OleDb":
                                objFactory = OleDbFactory.Instance;
                                break;
                            case "System.Data.OracleClient":
                                objFactory = OracleClientFactory.Instance;
                                break;
                            case "System.Data.Odbc":
                                objFactory = OdbcFactory.Instance;
                                break;
                        }
                        break;
     
                }
                objConnection = objFactory.CreateConnection();
                objCommand = objFactory.CreateCommand();
     
                objConnection.ConnectionString = strConnectionString;
                objCommand.Connection = objConnection;
            }
     
            public DatabaseHelper(Providers provider)
                : this(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString, provider)
            {
            }
     
            public DatabaseHelper(string connectionstring)
                : this(connectionstring, Providers.SqlServer)
            {
            }
     
            public DatabaseHelper()
                : this(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString, Providers.ConfigDefined)
            {
            }
     
            public bool HandleErrors
            {
                get
                {
                    return boolHandleErrors;
                }
                set
                {
                    boolHandleErrors = value;
                }
            }
     
            public string LastError
            {
                get
                {
                    return strLastError;
                }
            }
     
            public bool LogErrors
            {
                get
                {
                    return boolLogError;
                }
                set
                {
                    boolLogError = value;
                }
            }
     
            public string LogFile
            {
                get
                {
                    return strLogFile;
                }
                set
                {
                    strLogFile = value;
                }
            }
     
            public int AddParameter(string name, object value)
            {
                DbParameter p = objFactory.CreateParameter();
                p.ParameterName = name;
                p.Value = value;
                return objCommand.Parameters.Add(p);
            }
     
            public int AddParameter(DbParameter parameter)
            {
                return objCommand.Parameters.Add(parameter);
            }
     
            public DbCommand Command
            {
                get
                {
                    return objCommand;
                }
            }
     
            public void BeginTransaction()
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                objCommand.Transaction = objConnection.BeginTransaction();
            }
     
            public void CommitTransaction()
            {
                objCommand.Transaction.Commit();
                objConnection.Close();
            }
     
            public void RollbackTransaction()
            {
                objCommand.Transaction.Rollback();
                objConnection.Close();
            }
     
            public int ExecuteNonQuery(string query)
            {
                return ExecuteNonQuery(query, CommandType.Text, ConnectionState.CloseOnExit);
            }
     
            public int ExecuteNonQuery(string query, CommandType commandtype)
            {
                return ExecuteNonQuery(query, commandtype, ConnectionState.CloseOnExit);
            }
     
            public int ExecuteNonQuery(string query, ConnectionState connectionstate)
            {
                return ExecuteNonQuery(query, CommandType.Text, connectionstate);
            }
     
            public int ExecuteNonQuery(string query, CommandType commandtype, ConnectionState connectionstate)
            {
                objCommand.CommandText = query;
                objCommand.CommandType = commandtype;
                int i = -1;
                try
                {
                    if (objConnection.State == System.Data.ConnectionState.Closed)
                    {
                        objConnection.Open();
                    }
                    i = objCommand.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    HandleExceptions(ex);
                }
                finally
                {
                    objCommand.Parameters.Clear();
                    if (connectionstate == ConnectionState.CloseOnExit)
                    {
                        objConnection.Close();
                    }
                }
     
                return i;
            }
     
            public object ExecuteScalar(string query)
            {
                return ExecuteScalar(query, CommandType.Text, ConnectionState.CloseOnExit);
            }
     
            public object ExecuteScalar(string query, CommandType commandtype)
            {
                return ExecuteScalar(query, commandtype, ConnectionState.CloseOnExit);
            }
     
            public object ExecuteScalar(string query, ConnectionState connectionstate)
            {
                return ExecuteScalar(query, CommandType.Text, connectionstate);
            }
     
            public object ExecuteScalar(string query, CommandType commandtype, ConnectionState connectionstate)
            {
                objCommand.CommandText = query;
                objCommand.CommandType = commandtype;
                object o = null;
                try
                {
                    if (objConnection.State == System.Data.ConnectionState.Closed)
                    {
                        objConnection.Open();
                    }
                    o = objCommand.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    HandleExceptions(ex);
                }
                finally
                {
                    objCommand.Parameters.Clear();
                    if (connectionstate == ConnectionState.CloseOnExit)
                    {
                        objConnection.Close();
                    }
                }
     
                return o;
            }
     
            public DbDataReader ExecuteReader(string query)
            {
                return ExecuteReader(query, CommandType.Text, ConnectionState.CloseOnExit);
            }
     
            public DbDataReader ExecuteReader(string query, CommandType commandtype)
            {
                return ExecuteReader(query, commandtype, ConnectionState.CloseOnExit);
            }
     
            public DbDataReader ExecuteReader(string query, ConnectionState connectionstate)
            {
                return ExecuteReader(query, CommandType.Text, connectionstate);
            }
     
            public DbDataReader ExecuteReader(string query, CommandType commandtype, ConnectionState connectionstate)
            {
                objCommand.CommandText = query;
                objCommand.CommandType = commandtype;
                DbDataReader reader = null;
                try
                {
                    if (objConnection.State == System.Data.ConnectionState.Closed)
                    {
                        objConnection.Open();
                    }
                    if (connectionstate == ConnectionState.CloseOnExit)
                    {
                        reader = objCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    }
                    else
                    {
                        reader = objCommand.ExecuteReader();
                    }
     
                }
                catch (Exception ex)
                {
                    HandleExceptions(ex);
                }
                finally
                {
                    objCommand.Parameters.Clear();
                }
     
                return reader;
            }
     
            public DataSet ExecuteDataSet(string query)
            {
                return ExecuteDataSet(query, CommandType.Text, ConnectionState.CloseOnExit);
            }
     
            public DataSet ExecuteDataSet(string query, CommandType commandtype)
            {
                return ExecuteDataSet(query, commandtype, ConnectionState.CloseOnExit);
            }
     
            public DataSet ExecuteDataSet(string query, ConnectionState connectionstate)
            {
                return ExecuteDataSet(query, CommandType.Text, connectionstate);
            }
     
            public DataSet ExecuteDataSet(string query, CommandType commandtype, ConnectionState connectionstate)
            {
                DbDataAdapter adapter = objFactory.CreateDataAdapter();
                objCommand.CommandText = query;
                objCommand.CommandType = commandtype;
                adapter.SelectCommand = objCommand;
                DataSet ds = new DataSet();
                try
                {
                    adapter.Fill(ds);
                }
                catch (Exception ex)
                {
                    HandleExceptions(ex);
                }
                finally
                {
                    objCommand.Parameters.Clear();
                    if (connectionstate == ConnectionState.CloseOnExit)
                    {
                        if (objConnection.State == System.Data.ConnectionState.Open)
                        {
                            objConnection.Close();
                        }
                    }
                }
                return ds;
            }
     
            private void HandleExceptions(Exception ex)
            {
                if (LogErrors)
                {
                    WriteToLog(ex.Message);
                }
                if (HandleErrors)
                {
                    strLastError = ex.Message;
                }
                else
                {
                    throw ex;
                }
            }
     
            private void WriteToLog(string msg)
            {
                StreamWriter writer = File.AppendText(LogFile);
                writer.WriteLine(DateTime.Now.ToString() + " - " + msg);
                writer.Close();
            }
     
            public void Dispose()
            {
                objConnection.Close();
                objConnection.Dispose();
                objCommand.Dispose();
            }
        }
     
        public enum Providers
        {
            SqlServer, OleDb, Oracle, ODBC, ConfigDefined
        }
     
        public enum ConnectionState
        {
            KeepOpen, CloseOnExit
        }
    }
     
    using System.Data.OracleClient 报错
    解决方案资源管理器 -- 鼠标右键 引用 -- 添加引用 -- .NET选项卡 System.Data.OracleClient
     

    在使用该类的同时需要在web.config中配置connectionStrings节,以下为sql的连接字符串
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <connectionStrings>
        <add name="connectionstring" connectionString="data source=.\sqlexpress;initial catalog=northwind;integrated security=SSPI" providerName="System.Data.SqlClient"/>
      </connectionStrings>
    </configuration>

    举几个该类的使用例子:
    1.指明了数据库类型。(OleDb,在web.config配置好为OleDb的数据库)
                DatabaseHelper db = new DatabaseHelper(Providers.OleDb);
                db.AddParameter("@country", "USA");
                object obj=db.ExecuteScalar("select count(*) from customers where
    country=@country");
                Console.WriteLine("No. of Customers from USA :" + obj.ToString());
                Console.ReadLine();
    2.未指明数据库类型。(在web.config配置好据库连接)
                DatabaseHelper db = new DatabaseHelper();
                db.AddParameter("@country", "USA");
                SqlDataReader reader = (SqlDataReader)db.ExecuteReader("select companyname from customers where
    country=@country");
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetString(0));
                }
                reader.Close();
                Console.ReadLine();
    3.文件操作
                DatabaseHelper db = new DatabaseHelper();
                db.LogErrors = true;
               
    db.LogFile=@"D:\Bipin\Errorlog.txt";

                db.AddParameter("@country", "USA");
                object obj = db.ExecuteScalar("select count(*) from customerstable where
    country=@country");
                Console.WriteLine("Total customers in USA :" + obj.ToString());
                Console.ReadLine();

  • 相关阅读:
    快捷JS PHP
    css userAgent (简易浏览器区分) PHP
    http://fw.qq.com/ipaddress PHP
    JS竖排文字 PHP
    奇怪的body PHP
    使用36进制,无损压缩GUID到26位 PHP
    链接<a>执行JS PHP
    纯JS省市区三级联动 PHP
    Table 样式 PHP
    Exceeded storage allocation. The server response was: 4.3.1 Message size exceeds fixed maximum message size
  • 原文地址:https://www.cnblogs.com/Hdsome/p/2003210.html
Copyright © 2020-2023  润新知