CSDN博客

img xinyulou

数据访问层的第一个类(针对sqlserver)

发表于2004/6/23 11:07:00  1089人阅读

数据访问的服务类 只在数据访问组建内可用

internal class SQLServer
 {
  private SqlConnection connection;
  private static SQLServer sqlServer;
  private SqlTransaction sqlTransaction;
  private bool inTransaction;
  private SQLServer()
  {
   connection = new SqlConnection(GetConnectionString());
   inTransaction = false;
  }
  private string GetConnectionString()
  {
   string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
   //如果加密可在这里解密
   return ConnectionString;
  }

  /// <summary>
  /// 数据库的一个连接
  /// </summary>
  public SqlConnection Connection
  {
   get
   {
    if(connection == null)
     connection = new SqlConnection(GetConnectionString());
    return connection;
   }
  }
  /// <summary>
  /// 打开连接
  /// </summary>
  public void OpenConnection()
  {
   if(connection.State.ToString().ToUpper() != "OPEN")
    connection.Open();
  }
  /// <summary>
  /// 关闭连接
  /// </summary>
  public void CloseConnection()
  {
   if(connection.State.ToString().ToUpper() == "OPEN")
    connection.Close();
  }
  /// <summary>
  /// 事务
  /// </summary>
  public SqlTransaction SqlTran
  {
   get{return sqlTransaction;}
  }
  
  /// <summary>
  /// 开始事务
  /// </summary>
  public void BeginTransaction()
  {
   sqlTransaction = connection.BeginTransaction();
   inTransaction = true;
  }
  /// <summary>
  /// 提交事务
  /// </summary>
  public void CommitTransaction()
  {
   if(sqlTransaction != null)
    sqlTransaction.Commit();
   inTransaction = false;
  }
  /// <summary>
  /// 回滚事务
  /// </summary>
  public void RollbackTransaction()
  {
   if(sqlTransaction != null)
    sqlTransaction.Rollback();
   inTransaction = false;
  }  

  /// <summary>
  /// 获取单一的对象引用
  /// </summary>
  /// <returns>SQLServer对象引用</returns>
  public static SQLServer Instance()
  {
   if(sqlServer == null)
   {
    sqlServer = new SQLServer();
   }
   return sqlServer;
  }  
 }

0 0

相关博文

我的热门文章

img
取 消
img