对访问数据库的链接字符串的封装(MS什么都在封装,弄的我们原来越方(弱)便(智)),好吧,你可以解释说可以方便的更改链接只更改配置,而不用动主程序------隔离(隔离--保护;搞过配电的应该不陌生吧)
我还是比较信任MSDN的先上ConfigurationManager 类的两个属性吧,两个属性都能达到目的
上例子
AppSettings:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> </configSections> <appSettings> <add key="CarManager.Properties.Settings.DataConnectionString" value="Data Source=RTDZ-006;Initial Catalog=DATA;User ID=TTNZ;Password=12345" /> </appSettings> </configuration>
链接
SqlConnection Conn = new SqlConnection(ConfigurationManager.AppSettings[0].ToString());
————————————————————————————————
ConnectionStrings
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="myconn" connectionString="Data Source=.;Initial Catalog=Northwind; Persist Security Info=True;User ID=sa;Password=110"/> </connectionStrings> </configuration>
链接
string connstr = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
————————————————————————————————————
注意:using System.Configuration;要添加
引用要添加System.Configuration
时间: 2024-11-01 14:17:05