如何处理SQLite查询返回的数据?附C#代码示例
处理SQLite查询返回的玩家属性数据的方案
看起来你已经完成了查询的基础部分,但现有的Dictionary<int, int>没法满足“一个玩家对应多个能力属性”的需求——毕竟同一个玩家会有多条不同ability_id的记录,得调整数据结构,同时还要注意资源安全和代码健壮性。我给你梳理几个实用的处理方案:
1. 选对合适的数据结构
推荐用嵌套字典:Dictionary<int, Dictionary<int, int>>,外层键是player_id,内层字典的键是ability_id,值是对应的属性值value。这样你能快速通过玩家ID找到他的所有能力属性,逻辑也清晰。
2. 完善代码逻辑(含资源安全)
一定要用using语句自动释放IDbCommand和IDataReader,避免数据库资源泄漏。然后在循环里处理每条记录:
private Dictionary<int, Dictionary<int, int>> GetAllPlayerAttributesFromDB() { var playerAttributes = new Dictionary<int, Dictionary<int, int>>(); // using块自动释放命令资源 using (IDbCommand dbcmd = dbconn.CreateCommand()) { string sqlQueryPlayer = "SELECT player_id, ability_id, value FROM playerabilities"; dbcmd.CommandText = sqlQueryPlayer; // using块自动释放读取器资源 using (IDataReader reader = dbcmd.ExecuteReader()) { while (reader.Read()) { // 用列名获取索引,比硬写0/1/2更安全(SQL列顺序变了也不会出错) int playerId = reader.GetInt32(reader.GetOrdinal("player_id")); int abilityId = reader.GetInt32(reader.GetOrdinal("ability_id")); int value = reader.GetInt32(reader.GetOrdinal("value")); // 处理玩家条目:如果玩家不在字典里,先创建他的能力字典 if (!playerAttributes.ContainsKey(playerId)) { playerAttributes[playerId] = new Dictionary<int, int>(); } // 添加/更新能力值(根据业务需求,可加重复判断避免覆盖) if (!playerAttributes[playerId].ContainsKey(abilityId)) { playerAttributes[playerId][abilityId] = value; } else { // 可选:处理重复记录,比如覆盖或打日志 playerAttributes[playerId][abilityId] = value; // Debug.WriteLine($"玩家{playerId}的能力{abilityId}存在重复,已覆盖值"); } } } } return playerAttributes; }
3. 额外优化建议
- 空值处理:如果数据库字段允许NULL,先检查是否为空再取值,比如:
int value = reader.IsDBNull(reader.GetOrdinal("value")) ? 0 : reader.GetInt32(reader.GetOrdinal("value")); - 自定义类封装:如果业务逻辑复杂,建议创建实体类来封装数据,可读性更好:
然后用public class PlayerAbilitySet { public int PlayerId { get; set; } public Dictionary<int, int> AbilityValues { get; set; } = new Dictionary<int, int>(); }Dictionary<int, PlayerAbilitySet>来存储,后续扩展属性也更方便。 - 异常捕获:可以给方法加
try-catch块,捕获SQL操作可能出现的异常(比如连接断开、语法错误),记录日志或者返回友好提示。
4. 使用示例
拿到数据后,你可以这样快速访问:
var allPlayerAttrs = GetAllPlayerAttributesFromDB(); // 获取玩家1001的所有能力 if (allPlayerAttrs.TryGetValue(1001, out var player1001Abilities)) { foreach (var (abilityId, value) in player1001Abilities) { Console.WriteLine($"玩家1001的能力{abilityId}值为{value}"); } }
内容的提问来源于stack exchange,提问作者basti12354
相关产品推荐
相关产品推荐

