C# 在 asp.net 中从 Web.config 获取连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12490348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Connection String from Web.config in asp.net
提问by Ammar Asjad
I want to know the ways to get connection string from web.config file in asp.net.
我想知道从asp.net 中的web.config 文件获取连接字符串的方法。
I just only know the below way .
我只知道下面的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace Sherserve.DataAccessLayer
{
public class DBGateway
{
public static string conString;
public DBGateway()
{
conString = ConfigurationManager.ConnectionStrings["test"].ToString();
}
}
}
采纳答案by Shadow Wizard is Ear For You
Using the ConfigurationManager.ConnectionStringsis about the only proper way, to use it properly with sanity check you can have such code:
使用ConfigurationManager.ConnectionStringsis 是唯一正确的方法,要通过健全性检查正确使用它,您可以拥有这样的代码:
public DBGateway()
{
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["test"];
if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
throw new Exception("Fatal error: missing connecting string in web.config file");
conString = mySetting.ConnectionString;
}
This will throw useful error in case the connection string is missing, instead of cryptic "null object" error.
如果连接字符串丢失,这将抛出有用的错误,而不是神秘的“空对象”错误。
Worth to mention that the ConnectionStringSettingsclass is overriding the ToString()method:
值得一提的是,ConnectionStringSettings该类正在覆盖该ToString()方法:
public override string ToString()
{
return this.ConnectionString;
}
So it means that using ConfigurationManager.ConnectionStrings["test"].ToString()is the same like ConfigurationManager.ConnectionStrings["test"].ConnectionStringhowever you still better perform sanity check and personally it looks cleaner to use the actual property and not depend on the class to give it.
所以这意味着 usingConfigurationManager.ConnectionStrings["test"].ToString()是一样的,ConfigurationManager.ConnectionStrings["test"].ConnectionString但是你仍然可以更好地执行健全性检查,而且就个人而言,使用实际属性看起来更干净,而不是依赖于提供它的类。
回答by RL89
Here is the whole solution:-
这是整个解决方案:-
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
DataSet ds = new DataSet();
try
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, con);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
con.Open();
dataAdapter.Fill(ds, "table");
return ds;
}
catch (Exception ex)
{
}
finally
{
if (con.State == System.Data.ConnectionState.Open)
con.Close();
}
This is how you can fetch records from database into datatable.
这就是您如何从数据库中获取记录到数据表中的方法。
Hope this is what you were looking for.
希望这就是你要找的。
回答by mRizvandi
I have a method on my WebAssistant Class. i have a key on appSettings that contain my WebAppName, check the below line:
我的 WebAssistant 类上有一个方法。我在 appSettings 上有一个包含我的 WebAppName 的密钥,请检查以下行:
<add key="DOMAIN_NAME" value="mRizvandi.com"/>
and my connection name alwyas has "DomainName"+"DBConnectionString" template such as:
并且我的连接名称 alwyas 具有“DomainName”+“DBConnectionString”模板,例如:
<add name="mRizvandiDBConnectionString" connectionString=...
Ok, everything are ready to get connectionstring without pass any string.
好的,一切准备就绪,无需传递任何字符串即可获取连接字符串。
public static string GetDBConnectionString()
{
string retValue = "";
string domainUrl = "";
string connectionKey = "";
string dbConnectionString = "";
domainUrl = GetDomainUrl();
connectionKey = domainUrl.Substring(0, domainUrl.IndexOf(".")) + "DBConnectionString";
dbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionKey].ToString();
retValue = dbConnectionString;
return retValue;
}
I hope would be helpful.
我希望会有所帮助。
回答by Carlos E
Following code works for me. I've added the exception in case connectionString not founded in web.config
以下代码对我有用。我在 web.config 中没有建立 connectionString 的情况下添加了例外
web.config:
网络配置:
<configuration>
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=myaddress;Initial Catalog=MyCatalog;User ID=myuser;Password=pass;Encrypt=True;TrustServerCertificate=False"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
In my connection class:
在我的连接类中:
static internal string GetSqlConnectionString(){
try {
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings("DataBaseConnection");
if (mySetting == null)
throw new Exception("Database connection settings have not been set in Web.config file");
return mySetting.ConnectionString;
} catch (Exception ex) {
throw;
}}
回答by K.M.
Try
尝试
string ConString = System.Configuration.ConfigurationManager.ConnectionStrings[ConfigurationManager.ConnectionStrings.Count -1].ConnectionString;

