gpt4 book ai didi

c# - 循环遍历 MySql reader 中的每个列名称和值?

转载 作者:行者123 更新时间:2023-11-29 19:13:41 26 4
gpt4 key购买 nike

下面我正在使用 MySqlDataReader,并且想知道如何循环遍历所有列名称和值,并将它们添加到 <string,string> 中。字典中按键和值表示列名和列值?我的代码如下,展示了我如何使用阅读器。

protected bool TryLoadPlayerData(PlayerConnection playerConnection, string sso)
{
try
{
SetPlayer(playerConnection);

using (var databaseConnection = Hariak.HariakServer.Database.NewDatabaseConnection)
{
databaseConnection.SetQuery("SELECT * FROM `users` WHERE `auth_ticket` = @sso LIMIT 1;");
databaseConnection.AppendParameter("sso", sso);


using (MySqlDataReader reader = databaseConnection.ExecuteReader())
{
while (reader.Read())
{
// loop through columns here...
}
}
}

Logger.Info("Loaded PlayerData for " + SelectColumn("username"));
return true;
}
catch (Exception exception)
{
Logger.Error(exception, "Failed to load PlayerData for player.");
return false;
}
}

最佳答案

我要做的只是循环遍历所有 FieldCount,这允许您获取每个返回行的索引,然后使用 GetNameGetValue 将它们添加到字典中>

protected bool TryLoadPlayerData(PlayerConnection playerConnection, string sso)
{
try
{
SetPlayer(playerConnection);

using (var databaseConnection = Hariak.HariakServer.Database.NewDatabaseConnection)
{
databaseConnection.SetQuery("SELECT * FROM `users` WHERE `auth_ticket` = @sso LIMIT 1;");
databaseConnection.AppendParameter("sso", sso);


using (MySqlDataReader reader = databaseConnection.ExecuteReader())
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
for (int i = 0; i < reader.FieldCount; i++)
{
dictionary.Add(reader.GetName(i), reader.GetValue(i));
}
}
}

Logger.Info("Loaded PlayerData for " + SelectColumn("username"));
return true;
}
catch (Exception exception)
{
Logger.Error(exception, "Failed to load PlayerData for player.");
return false;
}
}

关于c# - 循环遍历 MySql reader 中的每个列名称和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42881309/

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