ADO.NET 连接字符串错误
首先,我是 C# 编程新手。 我创建了一个专用类,用于从 Visual Studio 2010 中 Web 服务应用程序的 app.config 获取连接字符串,如下代码所示。
在构建代码时,我通过 catch 块收到以下错误:
“名称‘连接’在当前上下文中不存在”。
显然连接超出了范围。
- 我该如何避免这个错误?
- 这里使用的 Dispose 方法是否正确?
public class FCSConnection : IDisposable
{
public string GetDefaultConnectionString()
{
string DefaultConnectionString = null;
try
{
DefaultConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection connection = new SqlConnection(DefaultConnectionString);
connection.Open();
return DefaultConnectionString;
}
catch (Exception)
{
if (DefaultConnectionString != null)
{
connection.Dispose();
}
}
return DefaultConnectionString;
}
public void Dispose()
{
throw new NotImplementedException();
}
}
Firstly, am new to C# programming.
I have created a dedicated class to get the connection string from the app.config of a Web Services application in Visual Studio 2010 as per the code below.
On building the code I get the following error via the catch block:
"The name 'connection' does not exist in the current context".
Obviously connection is going out of scope.
- How do I avoid this error?
- Is the Dispose method being used correctly here?
public class FCSConnection : IDisposable
{
public string GetDefaultConnectionString()
{
string DefaultConnectionString = null;
try
{
DefaultConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection connection = new SqlConnection(DefaultConnectionString);
connection.Open();
return DefaultConnectionString;
}
catch (Exception)
{
if (DefaultConnectionString != null)
{
connection.Dispose();
}
}
return DefaultConnectionString;
}
public void Dispose()
{
throw new NotImplementedException();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确切的编译器消息引用您的
catch
语句:这里,
connection
是一个未知名称,因为它是在try
块内声明的。至于你的整个代码,我认为它也是错误的。如果您希望您的
FCSConnection
类封装 SQL 连接,您应该将connection
声明为私有成员,然后将其处置在您的Dispose()
中方法。The exact compiler message refers to your
catch
statement:Here,
connection
is an unknown name, because it's declared inside thetry
block.As for your entire code, I think it's also wrong. If you want your
FCSConnection
class to encapsulate the SQL connection, you should declareconnection
as a private member and then dispose it in yourDispose()
method.