string connectionString = "Server=localhost;Database=mydatabase;Uid=myusername;Pwd=mypassword;"; MySqlConnection connection = new MySqlConnection(connectionString); connection.Open();
MySqlCommand command = new MySqlCommand("SELECT id, name FROM customers", connection); MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); string name = reader.GetString(1); Console.WriteLine("{0}\t{1}", id, name); } reader.Close();In this example, we create a MySqlCommand object that represents our SELECT statement and execute it using the ExecuteReader method. We then loop over the results using the Read method on the MySqlDataReader object and extract the values from each row using the GetInt32 and GetString methods. Overall, the MySqlConnection class is a convenient way to connect to and query MySQL databases in C#.