【问题标题】:Getting multiple MySQL Query results on Visual C# Console App在 Visual C# 控制台应用程序上获取多个 MySQL 查询结果
【发布时间】:2014-02-18 03:29:46
【问题描述】:

我正在尝试在 Visual C# 控制台应用程序上打印 MySQL 查询的结果。正如您在下面看到的那样,我能够在一行上获得多个列,但我想知道如何获得多个结果(行)。你看,我的表里有更多符合查询条件的记录。有人可以帮帮我吗?

    class Program
{
    static void Main(string[] args)
    {

        string ConnectionString = "Server=localhost; Database=world; Uid=root; Pwd=password"; // giving connection string
        MySqlConnection connection = new MySqlConnection(ConnectionString); 
        MySqlCommand cmd = connection.CreateCommand(); 
        cmd.CommandText = "SELECT name, population FROM city where population > 4000000"; 

        try 
        { 
        connection.Open(); 
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        MySqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine("City name is: " + reader["name"].ToString() + " " + reader["population"].ToString());
            Console.Read();
        }

    }

【问题讨论】:

  • 在 while 循环中真的需要 Console.Read() 吗?你知道这个等待用户输入的块吗?这可能是您只看到一个结果的原因吗?
  • 您说得对,您能正式回复一下,以便我接受您的问题吗?它现在正在工作。谢谢。

标签: c# mysql visual-studio


【解决方案1】:

您对 Console.Read() 的调用阻塞了 while 循环,因此您只需将一行打印到控制台,然后等待用户输入。

干杯

【讨论】:

    【解决方案2】:

    您想删除 Console.Read();,它阻止您的应用程序继续运行,直到它读取控制台上的另一个字符输入。

    其他需要考虑的事项:Using statements 确保在对象不再使用时释放由 MySql 对象 消耗的非托管资源。使用Parameterized queries(又名Prepared Statements),因为它们性能更好且更安全。

       string sql = "SELECT name, population FROM city WHERE population > @population"
       using (var conn = new MySqlConnection(/*Connection String*/))
       { 
            conn.Open();
            using (var cmd  = new MySqlCommand(sql, conn))
            {
                 cmd.Parameters.AddWithValue("@population", 4000000);
                 using (var reader = cmd.ExecuteReader())
                 {
                     while (reader.Read())
                     {
                          Console.WriteLine("City: {0} Population: {1}", 
                                           reader["name"], reader["population"]);
                     }
                 }
            }
        }
    

    【讨论】:

      【解决方案3】:

      可能还有其他方法可以做到这一点,但我所知道的最好的方法是将数据读取器加载到数据表中。

      DataTable dt = new DataTable("City");
      dt.Fill(reader);
      
      foreach (DataRow row in dt.Rows){
        Console.WriteLine("City name is: " + row["name"].ToString() + " " + row["population"].ToString());
        Console.Read();
      }
      

      编辑 在回答时,我意识到 Console.Read() 可能是问题所在。这段代码可以工作,但需要为每一行提供控制台输入。

      【讨论】:

        猜你喜欢
        • 2013-12-24
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        • 1970-01-01
        • 2010-12-19
        • 2020-08-11
        • 1970-01-01
        相关资源
        最近更新 更多