程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 一個有KeepConnection開關的C#的Database類

一個有KeepConnection開關的C#的Database類

編輯:.NET實例教程
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();
}
}
}
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved