在code SQL Server连接字符串VS在ASP.NET站点配置文件 [英] SQL Server connection string in code vs config file in ASP.NET site
本文介绍了在code SQL Server连接字符串VS在ASP.NET站点配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经有一个连接字符串在我的配置文件
I already have a connection string in my config file
<connectionStrings>
<add
name="ConnectionString"
connectionString="Data Source=*;Initial Catalog=*;User ID=*;Password=*"
providerName=".NET Framework Data Provider for SQL Server" />
目前我只增加一个连接字符串在我的cs文件:
Currently I am just adding another connection string in my .cs file:
SqlConnection myConnection =
new SqlConnection("user id=*;password=*;server=localhost;");
我想使用的配置文件字符串来连接在.cs文件数据库中无需添加另一个字符串。我该怎么做?
I want to use config file string to connect to a database in the .cs file without adding another string. How can I do that?
using (SqlConnection cn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["MyDbConn"].ToString()))
这是code,我发现,有没有什么办法缩短?
This was the code I found, is there any shorter way?
推荐答案
不是真的,但你可以在自己的小助手功能,把它包:
Not really, but you could wrap it in its own little helper function:
private static string GetConnectionString(string name)
{
return WebConfigurationManager.ConnectionStrings[name].ConnectionString;
}
using (var cn = new SqlConnection(GetConnectionString("MyDbConn"))) { ... }
这篇关于在code SQL Server连接字符串VS在ASP.NET站点配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文