web.config中的連接字串,與大家分享。
在ASP.NET的web.config中,可以用兩種方式來寫連接字串的配置。
<configuration> <appSettings> <add key="connstr1" value="Data Source=.;Initial Catalog=DBName;Integrated Security=true"/> <add key="connstr2" value="........."> </appSettings> <connectionStrings> <add name="connstr3" connectionString="........" /> <add name="connstr4" connectionString="......" providerName="System.Data.Sqlclient" </connectionStrings></configuration>
如上代碼所示:兩種方式為appSettings和connectionStrings
appSettings:
①它是asp.net1.1的時候用的,在vs2003中用的
②裡面存的相當於索引值對的形式,key和value。不僅僅可以存連接字串,還可以儲存一些配置項。
③在appSettings中,不能使用ProviderName="System.Data......."(不過如果你要用也可以,只要寫在value裡面就可以了,當成值傳遞過去)
④在後台取值方式用代碼:
string conn=System.Configuration.ConfigurationManager.AppSettings["connstr";]
connectionStrings:
①它是asp.net2.0中新增的。
②裡面存的也類似於索引值對的形式,使用的是name和connectionString,一般就存連接字串。
③在connectionStrings中可以,可以使用providerName.
④在後台代碼,取值的方式:
string conn=System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
既然connectionStrings是2.0版本出來的,那它肯定比appsettings有好處了:
網上如是說:
① 可將連接字串加密,使用MS的一個加密工具即可。
② 可直接邦定的資料來源控制項,而不必寫代碼讀出來再賦值給控制項。
③ 可方便的更換資料庫平台,如換為Oracle資料庫,只需修改providerName
providerName它的作用是什麼呢?
我們先看一下providerName的參數值。
①providerName="System.Data.SqlClient" ----說明使用的是MSSQLServer資料庫②providerName="System.Data.SqlLite" ----說明使用的是SQLLite資料庫③providerName="System.Data.OracleClient" ----說明使用的是Oracle資料庫或providerName="System.Data.Oracle.DataAccess.Client" ----同上④providerName="System.Data.OleDb" ----說明使用的是Access資料庫
providerName可寫可不寫。
我們什麼時候用providerName呢?
比如,我們現在要做一個項目,以後會賣個兩個企業使用:A和B。這就有不確定因素了,A使用Oracle,B使用SQLserver。
所以,
①資料庫:我們需要建兩個庫,一個用oracle,一個用Sqlserver。
②程式:我們一般不去寫兩個系統讓他們使用,我們肯定會去判斷,先判斷他們使用的是什麼資料庫,然後再在程式裡執行什麼樣的資料庫指令碼。
③web.config代碼:
<configuration> <connectionStrings> <add name="connStr" connectionString="Data Source=.;Initial Catalog=mydb;Integrated Security=true" providerName="System.Data.SqlClient"/> </connectionStrings></configuration>
④程式碼:進行判斷,如果providerName="System.Data.SqlClient"則執行SQLServer的指令碼,如果providerName="System.Data.OracleClient"則調用Oracle的資料庫指令碼。
public static readonly string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ProviderName;public static string databaseType = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ProviderName;public static int ExecuteNonQuery(CommandType commandType, string commandText, params System.Data.OleDb.OleDbParameter[] parm){ int num = 0; if (databaseType == "System.Data.SqlClient") { //此處執行Microsoft SQLServer的資料庫指令碼 } else if (databaseType == "System.Data.OracleClient") { //此處執行Oracle的資料庫指令碼 } return num;}