[英]error: Does not exist in the current context
我试图在C#控制台应用程序中访问MySql数据库,只是为了让它打印几个值以确保其连接。 它不断给我一个“名称”阅读器”在当前上下文中不存在的错误。
这是我正在使用的代码...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using System.Data;
namespace sql_test
{
class Program
{
static void Main(string[] args)
{
string connectionString =
"Server=localhost;" +
"Database=DBname;" +
"User ID=DBID;" +
"Password=DBpass;" +
"Pooling=false;";
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
try
{
dbcon.Open();
}
catch(Exception ex1)
{
Console.WriteLine(ex1.Message);
}
IDbCommand dbcmd = dbcon.CreateCommand();
string sql =
"SELECT RoomId, RoomName " +
"FROM Resources";
dbcmd.CommandText = sql;
try
{
IDataReader reader = dbcmd.ExecuteReader();
}
catch (InvalidOperationException ex2)
{
Console.WriteLine(ex2.Message);
}
while (reader.Read())
{
string roomID = (string)reader["RoomId"];
string roomName = (string)reader["RoomName"];
Console.WriteLine("Name: " +
roomID + " " + roomName);
}
// clean up
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
dbcon = null;
}
}
}
显然我已经更改了mysql登录密码和服务器名称等,但是其他方面都相同...
没有错误的唯一“阅读器”是IDataReader之后第39行之后的那个。
任何帮助将非常感激。
问题来源:
reader
变量在try语句之后的下一个语句的变量范围之外。
1.简单但不好的解决方法:
在块外声明阅读器:
IDataReader reader = null;
try
{
reader = dbcmd.ExecuteReader();
}
catch (InvalidOperationException ex2)
{
Console.WriteLine(ex2.Message);
}
2.推荐的解决方案:
如果发生某些情况,先前的解决方案可能会导致NullReferenceException,因此最好将整个连接和处理代码放在try语句中,并将清理代码放在finally块中:
IDataReader reader = null;
IConnection dbconn = null;
try
{
dbcon = ...
reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string roomID = (string)reader["RoomId"];
string roomName = (string)reader["RoomName"];
Console.WriteLine("Name: " +
roomID + " " + roomName);
}
}
catch (InvalidOperationException ex2)
{
Console.WriteLine(ex2.Message);
}
finally
{
// clean up
if (reader != null)
reader.Close();
if (dbcmd != null)
dbcmd.Dispose();
// ...
}
无需在处理代码中将变量设置为null,在这种情况下(对于局部变量)不会有任何改变。
3.替代解决方案:
还有C# using语句,可简化资源处理:
using (IConnection connection = new Connection...)
{
using (ICommand command = new Command...)
{
// Do processing
}
}
但这对错误处理没有帮助-您仍然必须将代码放入try catch块中:
try
{
using (IConnection conn = ...)
{
}
}
catch (Exception exc) // !!! Catching Exception and not something more specific may become a source of problems
{
// Handle errors
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.