如何在ASP.NET中使用Connection字符串?

时间:2014-01-19 14:52:56

标签: c# sql-server ado.net

我是ASP的初学者。请帮助我这个简单的概念。如何在web.config中存储连接字符串以及如何在连接到SQL 2008 DB时在ADO.NET中使用它?

2 个答案:

答案 0 :(得分:0)

这个SO答案有一些关于连接字符串的好指针。 How to define a connection string to a SQL Server 2008 database?。 此MSDN文档http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx包含有关连接字符串的信息以及配置文件中的示例。

答案 1 :(得分:0)

您好请检查以下代码:

在Asp.Net 2.0中

 You can add a key inside appSettings. 

<appSettings>
<add key="ConnectionStringName" value="server=localhost; database=DatabaseName; uid=SqlInstanceUserName; password=SqlInstancePassword;" />
</appSettings>

To read the connection string: 

string connStr = ConfigurationSettings.AppSettings("ConnectionStringName");

在Asp.Net 3.5中

 You can add a key inside connectionStrings. 

<connectionStrings>
<add name="ConnectionStringName" connectionString="server=localhost; database=DatabaseName; uid=SqlInstanceUserName; password=Sq lInstancePassword;" />
</connectionStrings>

To read the connection string:

string connStr = ConfigurationManager.ConnectionStrings [“ConnectionStringName”]。ConnectionString;