連線字串的維護

一般來講,在開發應用程式的過程當中所使用的資料庫,會與正式上線時使用的資料庫不同。而正式的產品,如果提供給不同的客戶使用,也會使用各別不同的資料庫。

  而資料庫的切換,對應用程式來講只是更改連線字串。因此如何能有個方法將應用程式中所有使用到的資料庫連線字串做個集中管理,當有需要切換資料庫時,只要在一個地方更改,並且不必再重新建置應用程式,就變成非常重要了。

  首先,我們必須明瞭,想對某一特定的資料庫操作時必須提供那些連線資訊的字串。在下述的網站中提供了相當多種類的資料庫連線字串(Connection String)的列表,讀者可以將該網站「加到我的最愛」好方便隨時當遺忘連線字串的寫法時可立即查詢。

http://www.connectionstrings.com/

   當知道了,想連接某個資料庫時該使用那些連線字串時,接下來是該連線字串要寫在那裡。在Windows Form或WPF應用程式可寫在app.config,而ASP.NET應用程式可寫在web.config中,不管是寫在app.config或 web.config其語法及在程式中讀取的方法是完全一樣的。底下是一個例子。

<connectionStrings>
    <add name="PTracker"
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=PTracker;Integrated Security=True;"
         providerName="System.Data.SqlClient" />
    <add name="Security"
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Security;Integrated Security=True;"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  將連線字串寫好在設定檔(*.config)後,如何在程式中讀取該些字串呢?

Imports System.Configuration.ConfigurationManager

Public Module Database

  Public ReadOnly Property PTrackerConnection() As String
    Get
      Return ConnectionStrings("PTracker").ConnectionString
    End Get
  End Property

  Public ReadOnly Property SecurityConnection() As String
    Get
      Return ConnectionStrings("Security").ConnectionString
    End Get
  End Property

End Module

  由於在應用程式中有需要讀取連線字串的場合可能超過數十次、數百次,且有時一個應用程式可能同時需要使用數個資料庫,因此我們可以先寫個模組(Module)如上列的程式碼,將來在應用程式中只要寫:

Database.PTrackerConnection

即可得到如下的連線字串:

Data Source=.\SQLEXPRESS;Initial Catalog=PTracker;Integrated Security=True

將來若有需要切換資料庫而必須更改連線字串時,也只要在設定檔(*.config)改一次,不必重新建置應用程式,就能輕易地切換資料庫。

  或許,因為安全性的問題,有需要將放在設定檔(*.config)中的連線字串加密,這時只要修改一下前述的模組如下,在讀出字串後多一道解密的動作:

Imports System.Configuration.ConfigurationManager

Public Module Database

  Public ReadOnly Property PTrackerConnection() As String
    Get
      Return Crypto.Decrypt(ConnectionStrings("PTracker").ConnectionString)
    End Get
  End Property

  Public ReadOnly Property SecurityConnection() As String
    Get
      Return Crypto.Decrypt(ConnectionStrings("Security").ConnectionString)
    End Get
  End Property

End Module

  上述程式碼是增加了:Crypto.Decrypt的解密程序,而關於這些如何對字串加解密的方法,將留待另一篇文章講解。


posted on 2008/4/21 20:41 | 我要推薦 | 閱讀數 : 751 | 文章分類 [ 資料存取層-資料庫 ] 訂閱

Comments on this entry:

目前沒有回應.

回應:

標題:
姓名:
電子郵件: (將不會被顯示)
個人網頁:
 
 
Please add 7 and 2 and type the answer here: