位置:海鸟网 > IT > ASP.NET >

一个有KeepConnection开关的C#的Database类

using System;
using System.Data;
using System.Data.SqlClient;

namespace cnkk.Data
{
 /// <summary>
 /// SQL Database.
 /// </summary>
 public class Database : DisposableBase
 {
  private string connectionString;
  private SqlConnection connection;

  protected Database(string connectionString)
  {
   this.connectionString = connectionString;
  }

  protected Database(SqlConnection connection)
  {
   this.connection = connection;
  }

  protected override void DisposeManaged()
  {
   base.DisposeManaged ();

   this.connection.Dispose();
  }

  private SqlConnection GetConnection()
  {
   if ( KeepConnection )
   {
    return this.connection;
   }
   else
   {
    return new SqlConnection(ConnectionString);
   }
  }

  protected SqlConnection Connection
  {
   get { return this.connection; }
  }

  private int commandTimeout = 30;

  /// <summary>
  /// 设置等待命令执行的时间(以秒为单位)。
  /// </summary>
  public static int CommandTimeout
  {
   set
   {
    this.commandTimeout = value;
   }
  }

  /// <summary>
  /// Database connection string.
  /// </summary>
  public string ConnectionString
  {
   get { return connection.ConnectionString; }
  }


  private bool keepConnection = false;

  /// <summary>
  /// 保持数据库连接,设置为 true 可以提供更高数据库访问性能,但不保证是线程安全的。
  /// </summary>
  public virtual bool KeepConnection
  {
   get
   {
    return keepConnection;
   }

   set
   {
    if ( keepConnection != value )
    {
     keepConnection = value;

     if ( keepConnection == true )
     {
      if ( connection.State == ConnectionState.Closed )
       connection.Open();
     }
     else
     {
      connection.Close();
     }
    }
   }
  }
 }
}