This article describes how global variables are used in two asp.net projects. web.config files and gloab files. The following are described separately:
Method One: Web.config file
--Settings:
Adding key keys to the Web.config file is implemented by the tag, but appSettings tags are usually placed in ... tag outside. Cases:
<configration>
<appSettings>
<add key="connString1" value="server=localhost;user id=sa;pwd=;database=数据库名字"/>
<add key="connString2" value="provider=Microsoft.Jet.OleDb.4.0;Data Source=数据库路径"/>
</appSettings>
<system.web>
</system.web>
</configration>
--read:
To reference these database connection strings in code, You need to add a reference to the System.Configuration namespace that contains the ConfigurationSettings class in the namespace, and its static method ConfigurationSettings.AppSettings property to get the web.config text The section in the piece is set, and the value read is string type. For example:
using System.Configuration;
string conn1 = ConfigurationSettings.AppSettings["connString1"];
string conn2 = ConfigurationSettings.AppSettings["connString2"];
SQLConnection myConn1 = new SQLConnection(conn1);
OleDbConnection myConn2 = new OleDbConnection(conn2);
在VS2005中, ConfigurationSettings.AppSettings 可以换成 ConfigurationManager.AppSettings
Method Two: Gloab file
--Settings:
Adding in the global file
protected void Session_Start(Object sender, EventArgs e)
{
Session["sqlConnectionString"] = "uid=Username;pwd=password;database=MyTest;server=Localhost;Connect Timeout=300";
}
--read:
Application in code:
String strConnection=Session["sqlConnectionString"].ToString();
sqlConnection_1=new SqlConnection(strConnection);
Recommended to use the first way! More flexible, hahaha.