gpt4 book ai didi

C# MySQL 在 DataReader while 循环中的第二个 DataReader

转载 作者:可可西里 更新时间:2023-11-01 07:59:35 28 4
gpt4 key购买 nike

正如您可能已经从标题中猜到的,我正在尝试这样做:

    #region check new nations
private void checknewnations()
{
addtolog("server","Checking for new nations");
string sql = "SELECT * FROM " + variables.tbl_nations + " WHERE nations_new=0";
MySqlCommand cmd = new MySqlCommand(sql, connection);
MySqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
addtolog("mysql",reader["nations_name"].ToString());

int nation_ID = int.Parse(reader["nations_ID"].ToString());
string nation_name = reader["nations_name"].ToString();
string user_ID = reader["nations_user"].ToString();


addnation(nation_ID, nation_name, user_ID);
}
addtolog("server","Finished checking for new nations.");
//connection.Close();
reader.Dispose();
}
#endregion

在 while 循环中调用它:

    #region addnation
private void addnation(int nationIDnot, string nationName, string userID)
{
string nationID = makesixdigits(nationIDnot);
string userName = "";

string sql = "SELECT * FROM " + variables.tbl_users + " WHERE users_ID=" + userID;
MySqlCommand cmd = new MySqlCommand(sql, connection);
MySqlDataReader reader = cmd.ExecuteReader();


while (reader.Read())
{
userName = reader["users_name"].ToString();
}
reader.Dispose();
addtolog("add", "[" + nationID.ToString() + "] " + nationName + " [" + userID + "] " + userName);
}
#endregion

这让我在第二个代码块(在 while 循环中调用的代码块)中出错,说已经有一个与连接关联的数据读取器。我如何才能让它发挥作用,因为我确信有办法。

最佳答案

DataReader 保持连接直到它遍历所有记录。试试这个

using(reader)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(reader);

foreach(DataRow row in dt.Rows)
{
addtolog("mysql",row["nations_name"].ToString());

int nation_ID = int.Parse(row["nations_ID"].ToString());
string nation_name = row["nations_name"].ToString();
string user_ID = row["nations_user"].ToString();


addnation(nation_ID, nation_name, user_ID);
}
}

这样两个阅读器就不会共享同一个连接

关于C# MySQL 在 DataReader while 循环中的第二个 DataReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11961682/

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