gpt4 book ai didi

c# - 嵌套数据读取器问题 mysql c#

转载 作者:可可西里 更新时间:2023-11-01 07:41:24 25 4
gpt4 key购买 nike

我已经编写了一个自定义类来处理对远程和本地 MySQL 数据库的数据库查询,但是当我执行嵌套循环时,我收到以下错误:

MySql.Data.MySqlClient.MySqlException was unhandled
Message=There is already an open DataReader associated with this Connection which must be closed first.
Source=MySql.Data
ErrorCode=-2147467259
Number=0

我的类(class)目前看起来像这样

public class MySQLManager
{
private MySqlConnection _MySQLRemoteConnection { get; set; }
public void setup(string remoteUser, string remotePass, string remoteServerAddress, string remoteDb, string localUser, string localPass, string localServerAddress, string localDb)
{
_remote_server_address = remoteServerAddress;
_remote_database = remoteDb;
_remote_username = remoteUser;
_remote_password = remotePass;
}
public void connect()
{
try
{
_MySQLRemoteConnection = new MySqlConnection() { ConnectionString = string.Format("server={0};database={1};uid={2};password={3};", _remote_server_address, _remote_database, _remote_username, _remote_password) };
_MySQLRemoteConnection.Open();
_RemoteConnection = true;
}
catch (MySqlException ex)
{
_RemoteConnection = false;
}
}
public MySqlCommand run(string query, List<MySqlParameter> dbparams = null)
{
connect();

MySqlCommand sql = getConnection().CreateCommand();
sql.CommandText = query;
if (dbparams != null)
{
if (dbparams.Count > 0)
{
sql.Parameters.AddRange(dbparams.ToArray());
}
}
//disconnect();
return sql;
}
public MySqlDataReader fetch(MySqlCommand cmd)
{
//connect();
var t = cmd.ExecuteReader();
//disconnect();
return t;
}

我正在运行以创建错误的代码,现在我明白我可以在单个查询中执行以下示例,这是一个用于重新创建错误的 EXAMPLE 查询,将其写入单个查询不会使用实例。

query = "SELECT field1 FROM tmp WHERE field1 < 3";
using (var sql = db.run(query))
{
txtResponse.Text += "Query ran" + nl;
using (var row = db.fetch(sql))
{
txtResponse.Text += "Query fetched" + nl;

db.connect();
while (row.Read())
{
txtResponse.Text += "Row : " + row[0].ToString() + nl;
query = "SELECT val1 FROM tmp2 WHERE field1 = '" + row[0].ToString() + "'";
//db.disconnect();
using (var sql2 = db.run(query))
{
txtResponse.Text += "Query ran" + nl;
db.disconnect();
using (var row2 = db.fetch(sql))
{
txtResponse.Text += "Query fetched" + nl;
db.connect();
while (row.Read())
{
txtResponse.Text += " Val : " + row2[0].ToString() + nl;
}
}
}
}
}
}

那么我该如何让第二个循环工作呢?

最佳答案

对于 SQL Server,您可以在连接字符串上使用 MultipleActiveResultSets=true,但这很可能不适用于 MySQL。

另一种选择是使用 2 个连接,一个用于每个数据读取器。

关于c# - 嵌套数据读取器问题 mysql c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11155879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com