[英]ASP.NET web development with C# : centralize the connection string
我是asp.net和C#的新手。 我在每个页面中都使用一个连接字符串来连接到数据库并获取结果(连接字符串显示在下面的代码中)。 有什么办法可以使连接字符串集中化? 这样我不必在每个页面中都调用它?
谁能帮我解决这个问题? 请..
con = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=ewadb;Integrated Security=SSPI");
//data = new SqlDataAdapter("SELECT * FROM deals", con);
//dset = new DataSet();
//data.Fill(dset, "deal");
您可以将连接字符串放在web.config文件中:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="default" connectionString="Data Source=localhost\sqlexpress;Initial Catalog=ewadb;Integrated Security=SSPI" />
</connectionStrings>
</configuration>
然后,可以使用ConfigurationManager类获取值:
ConfigurationManager.ConnectionStrings["default"].ConnectionString;
从架构上讲,您的页面不应直接处理数据访问。
有关n层架构的概述,请参见此处: http : //en.wikipedia.org/wiki/Multitier_architecture 。
您应该将其放置在web.config中。 这意味着您可以轻松地对其进行更改,并可以在任何地方一致地调用它。 请参阅下面的介绍。
http://msdn.microsoft.com/en-us/library/ms178411.aspx
另外一个简单的解释:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
1)使用web.config
文件将连接字符串存储为
<appSettings>
<add key="connString_MyDB" value="Server=localhost;Integrated Security=false;Database=WORLD;Asynchronous Processing=True;user=sa;password=123;"/>
</appSettings>
2)在您的班级中检索连接字符串调用
Private connString As String = System.Configuration.ConfigurationManager.AppSettings.Get("connString_MyDB").ToString
将连接字符串放入web.config
文件的配置部分。
<configuration>
<connectionStrings>
<add name="default" connectionString="your connection string" />
</connectionStrings>
</configuration>
使用以下代码访问页面中的连接字符串。
System.Configuration.ConfigurationManager.
ConnectionStrings["connectionStringName"].ConnectionString;
您可以像下面这样:
Web.Config中:
获取代码中的连接字符串:sqlConnection con = new sqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get(“ connection”));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.