.net连接字符

来源:互联网 发布:如何申请为淘宝达人 编辑:程序博客网 时间:2024/05/16 05:18

c#使用web.config配置中的连接字符串

What other way *is* there to do it?

Here's some pointers on using the Config file for your Connection Strings. It's different in VS2005 than it was in VS2003, but I'll show you both.

For VS2003:
Put the connection string in the appSettings section of the application configuration file (web.config for an app that uses Web Services or for ASP.NET app) and read it with the ConfigurationSettings.AppSettings property, see:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpgrfaccessingappsettingssection.asp


Basically, something like this;

<configuration>
  <appSettings>
    <add key="ConnectionString" value="server=(local);database=MyDataBase;uid=sa;pwd=123" />
  </appSettings>
</configuration>

If SQL Server isn't local, then just substitute the Server name for (local).

Get the connection string in your application using the Configuration Settings:

string cConnection = ConfigurationSettings.AppSettings["ConnectionString"];

For VS2005:
It's a little different now for VS2005, but the above stuff will still work (although you'll probably get a compiler warning about ConfigurationSettings.AppSettings being obsolete, but it will still work ok).

Your config file should look like this now:

<configuration>
  <connectionStrings>
    <add name="ConnectionForMyDatabase" connectionString="server=(local);database=MyDataBase;uid=sa;pwd=123" />
  </connectionStrings>
</configuration>

Get the connection string in your application using the new ConfigurationManager:

string cConnection = ConfigurationManager.ConnectionStrings["ConnectionForMyDatabase"].ConnectionString;
 

原创粉丝点击