ADO.net数据库连接实现方案(C#)

//全局的数据库连接类公用一个

public class DBConnection
    {///数据库连接类     
        private static string connectionstring = ConfigurationSettings.AppSettings["acceconstr"].ToString();
        private static OleDbConnection conn =null;
        private DBConnection()
        {///将构造函数设为private使其不能创建DBConnection实体
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        public static OleDbConnection GetInstance()
        {///创建数据库连接实体
            if(conn!=null)
            {
                return conn;
            }
            else
            {
                return new OleDbConnection(connectionstring);
            }
        }
        public static void DBConnectionTest(OleDbConnection conn)
        {///测试数据库连接
            try
            {
                conn.Open();
                if (conn.State == ConnectionState.Open)
                {
                    BaseOperate.ShowMessage("打开成功");
                }
                else
                {
                    BaseOperate.ShowMessage("未能打开");
                }
            }
            catch (Exception erro)
            {
                BaseOperate.ShowMessage(erro.Message + "数据库打开出错");
            }
            finally
            {
                conn.Close();
            }
        }

    }

 

App.config配置文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <!--连接MSSQLEXPRESS数据库字符串-->
        <add key="sqlconstr" value="DataSource=.\SQLEXPRESS;Database=AMMIS;Integrated Security=SSPI;" />
        <!--连接Access数据库字符串-->
        <add key="acceconstr" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AMMIS.mdb;" />
    </appSettings>
    <connectionStrings>
        <add name="sqlconstr" connectionString="DataSource=.\SQLEXPRESS;Database=AMMIS;Integrated Security=SSPI;"
        providerName="System.Data.SqlClient"/>
        <add name="acceconstr" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AMMIS.mdb;"
        providerName="SystemData.OleDb"/>
    </connectionStrings>
</configuration>

你可能感兴趣的:(数据库连接)