Skip to content

10.3 Reading points

  1. Change the code inside the if (connection != null) block as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    if (connection != null)
    {
        Console.WriteLine("Connection established!");
        string sql = "SELECT * FROM Point;";
        try
        {
            MySqlCommand command = new MySqlCommand(sql, connection);
            using MySqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                double x = reader.GetDouble("xcoordinate");
                double y = reader.GetDouble("ycoordinate");
                Console.WriteLine($"({x:F2}, {y:F2})");
            }
            connection.Close();
        }
        catch (MySqlException ex)
        {
            Console.WriteLine(ex);
        }
    }
    

    This is the standard way to read data from a database.

    • The query is in the string sql. In this case, all rows from the Point table are retrieved.
    • The results are returned in a MySqlDataReader.
    • The while-loop iterates through the rows. Columns are accessed by column name (as defined in Workbench).
    • After execution, the connection can be closed.
  2. Try some other queries, such as "SELECT * FROM Circle WHERE radius > 5" and display the radius of the returned circles. Adjust the code in the while-loop accordingly.