You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C#中执行多个MySQL查询,如何获取并打印所有查询结果?

解决C#中执行多MySQL查询仅获取第一个结果的问题

你的代码核心问题有两个:一是第二个查询创建了命令对象但未执行ExecuteReader()获取对应结果集,反而继续用第一个查询的reader读取;二是直接拼接SQL字符串存在严重的SQL注入风险。以下是修正后的实现方案:

修正步骤

  1. 为第二个查询单独创建MySqlDataReader,调用对应命令的ExecuteReader()获取结果
  2. 替换SQL字符串拼接为参数化查询,彻底避免注入风险
  3. 使用using语句管理数据库对象,确保资源自动释放,避免内存泄漏

完整修正代码

string wl_query = "select * from `tab1`";

// 使用using包裹Command和Reader,确保资源自动释放
using (MySqlCommand cmd = new MySqlCommand(wl_query, db.connectdb))
using (MySqlDataReader reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        // 读取第一个查询的结果
        string server = reader["server"].ToString();
        Console.WriteLine(server);
        string username = reader["username"].ToString();
        Console.WriteLine(username);
        string password = reader["password"].ToString();
        Console.WriteLine(password);
        string database = reader["database"].ToString();
        Console.WriteLine(database);
        
        // 强类型读取ID字段,避免类型转换错误
        int wl_config_id = reader.GetInt32(reader.GetOrdinal("wl_id"));

        // 第二个查询使用参数化写法
        string config_query = "SELECT * FROM `tab_config` where id = @ConfigId;";
        using (MySqlCommand config_cmd = new MySqlCommand(config_query, db.connectdb))
        {
            // 添加参数,替代字符串拼接
            config_cmd.Parameters.AddWithValue("@ConfigId", wl_config_id);
            
            // 执行第二个查询并获取结果集
            using (MySqlDataReader configReader = config_cmd.ExecuteReader())
            {
                while (configReader.Read())
                {
                    // 读取第二个查询的结果
                    string server_ip = configReader["server_ip"].ToString();
                    Console.WriteLine(server_ip);
                    string server_username = configReader["server_username"].ToString();
                    Console.WriteLine(server_username);
                    string user_password = configReader["password"].ToString();
                    Console.WriteLine(user_password);
                }
            }
        }
    }
}

额外说明

  • using语句会在代码块结束时自动释放MySqlCommand、MySqlDataReader等资源,无需手动调用Close()或Dispose()
  • 参数化查询不仅能防止SQL注入,还能让数据库缓存执行计划,提升重复查询的性能
  • 使用GetInt32等强类型读取方法,比直接ToString()更可靠,避免因字段类型不匹配导致的异常

内容的提问来源于stack exchange,提问作者Hsn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:25:56