DotNet访问和操作数据库

   经过长期的项目开发,我发现微软的企业库对数据库操作的性能是比较良好,并且对其进行了总结和归纳,现跟大家一起分享,希望能对需要的人有帮助.
 
DAOBase.cs
 
using System;
using System.Data;
using System.Data.SqlClient;
using TN.Data.SQLEngine;
namespace TN.Data.Access
{
 /// <summary>
 /// 数据存取组件基类
 /// </summary>
 public class DAOBase : IDisposable
 {
  /// <summary>
  /// DAO异常名称
  /// </summary>
  public const string DAO_EXCEPTION = "数据存取组件异常";
  /// <summary>
  /// 数据库操作引擎
  /// </summary>
  protected SQLServer m_sqlEngine = null;
  /// <summary>
  /// 构造方法
  /// </summary>
  public DAOBase()
  {
   //创建数据库操作引擎实例
   try
   {
                m_sqlEngine = new SQLServer(Global.ConfigureString);
   }
   catch(Exception e)
   {
    m_sqlEngine = null;
    throw e;
   }
  }
  /// <summary>
  /// 释放内存
  /// </summary>
  public void Dispose()
  {
   Dispose(true);
   GC.SuppressFinalize(true);
  }
  /// <summary>
  /// 虚拟释放内存
  /// </summary>
  /// <param name="disposing">释放标志</param>
  protected virtual void Dispose(bool disposing)
  {
   if (!disposing)
    return;
   if (m_sqlEngine != null)
    m_sqlEngine.Disposing();
  }
        /// <summary>
        ///
        /// </summary>
        /// <param name="strInfoMsg"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataSet LoadData(out string strErrText, string sql)
        {
            return m_sqlEngine.LoadData(sql, out strErrText);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="strInfoMsg"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public long ExecuteData(out string strErrText, string sql)
        {
            return m_sqlEngine.ExecuteNonQuery(sql, out strErrText);
        }
  /// <summary>
  /// 在MBO数据库引擎上启动事务
  /// </summary>
  /// <param name="strErrText">出错信息</param>
  /// <returns>如果成功,则返回True;否则,返回False</returns>
  public bool BeginTrans(out string strErrText)
  {
   return m_sqlEngine.BeginTrans(out strErrText);
  }
  /// <summary>
  /// 在MBO数据库引擎上提交事务
  /// </summary>
  /// <returns>如果成功,则返回True;否则,返回False</returns>
  public bool CommitTrans(out string strErrText)
  {
   return m_sqlEngine.CommitTrans(out strErrText);
  }
  /// <summary>
  /// 在MBO数据库引擎上回滚事务
  /// </summary>
  /// <returns>如果成功,则返回True;否则,返回False</returns>
        public void RollbackTrans()
        {
            m_sqlEngine.RollbackTrans();
        }
 }
}
DataAccess.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using TN.Data.Access;
namespace TN.Data.Access
{
    /// <summary>
    /// 数据访问操作
    /// </summary>
    public class DataAccess
    {
        /// <summary>
        /// 执行查询操作
        /// </summary>
        /// <param name="strErrText">出错信息</param>
        /// <param name="sql">执行Sql语句</param>
        /// <returns></returns>
        public static DataSet LoadData(out string strErrText, String sql)
        {
            using (DAOBase DaoBase = new DAOBase())
            {
                //假如开启事务失败则返回 -1
                if (!DaoBase.BeginTrans(out strErrText))
                    return null;
                DataSet dt = DaoBase.LoadData(out strErrText, sql);
                if (dt == null)
                {
                    DaoBase.RollbackTrans();
                }
                else
                {
                    DaoBase.CommitTrans(out strErrText);
                }
                return dt;
            }
        }
        /// <summary>
        /// 执行增、删、更新操作
        /// </summary>
        /// <param name="strInfoMsg">出错信息</param>
        /// <param name="sql">执行Sql语句</param>
        /// <returns>成功返回True,失败返回False</returns>
        public static bool ExecuteData(out string strErrText, string sql)
        {
            using (DAOBase DaoBase = new DAOBase())
            {
                //假如开启事务失败则返回 -1
                if (!DaoBase.BeginTrans(out strErrText))
                    return false;
                long nAffect = DaoBase.ExecuteData(out strErrText, sql);
                if (nAffect == -1)
                {
                    DaoBase.RollbackTrans();
                }
                else
                {
                    DaoBase.CommitTrans(out strErrText);
                }
                return nAffect >=0 ? true : false;
            }
        }
    }
}
SQLServer.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Logging;
namespace TN.Data.SQLEngine
{
    /// <summary>
    /// SQLServer数据库操作引擎
    /// </summary>
    public class SQLServer
    {
        private const string DATABASE_EXCEPTION = "数据库异常";
        private Database db = null;//数据库对象
        private DbConnection m_conn = null;//连接命令
        private DbTransaction m_trans = null;//事务
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="strConnectString">连接字符串</param>
        public SQLServer(string ConfigureString)
        {
            try
            {
                db = DatabaseFactory.CreateDatabase(ConfigureString);
                m_conn = db.CreateConnection();
                m_conn.Open();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 释放数据库引擎
        /// </summary>
        public void Disposing()
        {
            if (m_conn != null)
            {
                if (m_conn.State == ConnectionState.Open)
                {
                    m_conn.Close();
                }
            }
        }
        /// <summary>
        /// 启动事务
        /// </summary>
        /// <param name="strErrText">出错信息</param>
        /// <returns>成功返回True,否则返回False</returns>
        public bool BeginTrans(out string strErrText)
        {
            try
            {
                m_trans = m_conn.BeginTransaction();
                strErrText = string.Empty;
                return true;
            }
            catch (Exception)
            {
                strErrText = "开启事务失败!";
                return false;
            }
        }
        /// <summary>
        /// 提交事务
        /// </summary>
        public bool CommitTrans(out string strErrText)
        {
            try
            {
                if (m_trans != null)
                {
                    m_trans.Commit();
                    m_trans = null;
                }
            }
            catch (Exception)
            {
                strErrText = "提交事务失败!";
                return false;
            }
            strErrText = string.Empty;
            return true;
        }
        /// <summary>
        /// 回滚事务
        /// </summary>
        /// <returns>成功返回True,否则返回False</returns>
        public void RollbackTrans()
        {
            try
            {
                if (m_trans != null)
                {
                    m_trans.Rollback();
                    m_trans = null;
                }
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 读取数据集
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <param name="strErrText">出错信息</param>
        /// <returns>数据集</returns>
        public DataSet LoadData(string sql, out string strErrText)
        {
            try
            {
                DbCommand cmd = db.GetSqlStringCommand(sql);
                DataSet dt = db.ExecuteDataSet(cmd);
                strErrText = string.Empty;
                return dt;
            }
            catch (Exception e)
            {
                strErrText = e.Message;
                return null;
            }
        }
        /// <summary>
        /// 执行SQL查询语句
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <param name="strErrText">出错信息</param>
        /// <returns>影响行数</returns>
        public int ExecuteNonQuery(string sql, out string strErrText)
        {
            try
            {
                DbCommand cmd = db.GetSqlStringCommand(sql);
                int count = db.ExecuteNonQuery(cmd);
                strErrText = string.Empty;
                return count;
            }
            catch (Exception e)
            {
                strErrText = e.Message;
                return -1;
            }
        }
    }
}
App.config 配置如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>
  <connectionStrings>
    <add name="ConnectionString1" connectionString="Data Source=192.168.1.2;DataBase=TianNing;User ID=sa;PassWord="
      providerName="System.Data.SqlClient" />
    <add name="ConnectionString2" connectionString="Data Source=(local);DataBase=TianNing;User ID=sa;PassWord=yaojian"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>
 
Global.cs 全局类
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Windows.Forms;
namespace TN.Data
{
    /// <summary>
    /// 全局类
    /// </summary>
    public class Global
    {
        /// <summary>
        /// 服务器地址
        /// </summary>
        static string strServer = string.Empty;
        /// <summary>
        /// 用户名
        /// </summary>
        static string strUser = string.Empty;
        /// <summary>
        /// 密码
        /// </summary>
        static string strPwd = string.Empty;
        /// <summary>
        /// 数据库配置节点名称
        /// </summary>
        static string strConfigureString = string.Empty;
        /// <summary>
        /// 服务器地址
        /// </summary>
        public static string Server
        {
            get
            {
                return strServer;
            }
            set
            {
                strServer = value;
            }
        }
        /// <summary>
        /// 获得或者设置用户名
        /// </summary>
        public static string User
        {
            get
            {
                return strUser;
            }
            set
            {
                strUser = value;
            }
        }
        /// <summary>
        /// 获得或者设置密码
        /// </summary>
        public static string Password
        {
            get
            {
                return strPwd;
            }
            set
            {
                strPwd = value;
            }
        }
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                return "Data Source=" + strServer + ";DataBase=TianNing;User ID=" + strUser + ";PassWord=" + strPwd;
            }
        }
        /// <summary>
        /// 数据库配置节点名称
        /// </summary>
        public static string ConfigureString
        {
            get
            {
                return strConfigureString;
            }
            set
            {
                strConfigureString = value;
            }
        }
        /// <summary>
        /// 获得当前路径
        /// </summary>
        public static string GetCurrentAppPath
        {
            get
            {
                return Application.StartupPath;
            }
        }
        /// <summary>
        /// 显示提示信息框
        /// </summary>
        /// <param name="Content"></param>
        public static void ShowMsg(string Content)
        {
            MessageBox.Show(Content, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
       
        /// <summary>
        /// 询问框
        /// </summary>
        /// <param name="Content"></param>
        /// <returns></returns>
        public static DialogResult AskMsg(string Content)
        {
            return MessageBox.Show(Content, "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
        }
    }
}

你可能感兴趣的:(数据库,职场,访问,dotNet,休闲)