C# 为什么会出现此错误:ConnectionString 属性尚未初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18284217/
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
Why am I getting this error: The ConnectionString property has not been initialized
提问by thenextmogul
I have searched and tried everything but can't figure this one out. I am trying to do something simple but it seems as though I am doing something wrong. Basically, any user that has made a deposit, I want to return true, if they have not, I want to return false. This should be easy I suppose but I am stumped on this.
我已经搜索并尝试了一切,但无法弄清楚这一点。我正在尝试做一些简单的事情,但似乎我做错了什么。基本上,任何存款的用户,我都想返回true,如果他们没有,我想返回false。我想这应该很容易,但我对此感到困惑。
Here is the error:
这是错误:
The ConnectionString property has not been initialized.
ConnectionString 属性尚未初始化。
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
异常详细信息:System.InvalidOperationException:ConnectionString 属性尚未初始化。
Source Error:
源错误:
Line 59: Cmd.Parameters.AddWithValue("@UserID", userId);
Line 60: con.Open();
Line 61:
Line 62: result = (int)Cmd.ExecuteScalar();
Here is the top of the stack trace:
这是堆栈跟踪的顶部:
[InvalidOperationException: The ConnectionString property has not been initialized.] System.Data.SqlClient.SqlConnection.PermissionDemand() +4879939 System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection) +20 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122
[InvalidOperationException:ConnectionString 属性尚未初始化。] System.Data.SqlClient.SqlConnection.PermissionDemand() +4879939 System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection) +20 System.Data.ProviderBase.DbConnectionClosed.OpenConnection( DbConnection externalConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122
Here is my method for returning true or false:
这是我返回 true 或 false 的方法:
public static bool HasDeposit(int userId)
{
int result = 0;
//since executeScalar is intended to retreive only a single value
//from a query, we select the number of results instead of the email address
//of each matching result.
string queryTransaction = "SELECT COUNT(UserID) FROM Transaction WHERE TransactionTypeID = 6 AND UserID = @UserID";
string constr = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection con = new SqlConnection(constr);
SqlCommand Cmd = new SqlCommand(queryTransaction, con);
Cmd.Parameters.AddWithValue("@UserID", userId);
con.Open();
result = (int)Cmd.ExecuteScalar();
//returning a boolean comparator works like this :
//will return true if the result is greater than zero, but false if it is not.
con.Close();
return result > 0;
}
Any help / guidance on this would be much appreciated.
对此的任何帮助/指导将不胜感激。
采纳答案by Kane
If you have your connection strings in your configuration like this
如果您的配置中有这样的连接字符串
<connectionStrings>
<add name="ConnectionString" connectionString="data source=.;Initial Catalog=MyDatabase;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
Then you will need to use this method to access it System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
然后你需要使用这个方法来访问它 System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
You should also wrap your data access in using statements so that you don't leak connections and flood the pool. Here's an updated example with using statements.
您还应该在 using 语句中包装您的数据访问,这样您就不会泄漏连接并淹没池。这是一个带有 using 语句的更新示例。
public static bool HasDeposit(int userId)
{
//since executeScalar is intended to retreive only a single value
//from a query, we select the number of results instead of the email address
//of each matching result.
const string queryTransaction = "SELECT COUNT(UserID) FROM Transaction WHERE TransactionTypeID = 6 AND UserID = @UserID";
var constr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (var con = new SqlConnection(constr))
{
using (var cmd = new SqlCommand(queryTransaction, con))
{
cmd.Parameters.AddWithValue("@UserID", userId);
con.Open();
var result = (int)cmd.ExecuteScalar();
//returning a boolean comparator works like this :
//will return true if the result is greater than zero, but false if it is not.
return result > 0;
}
}
}
回答by Samiey Mehdi
In web.config :
在 web.config 中:
<appSettings>
<add key="ConnectionString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
</appSettings>
回答by rajquest
This error occurs when ConnectionString is null. Handle null value to fix this issue.
当 ConnectionString 为空时会发生此错误。处理空值以解决此问题。