using MySql.Data.MySqlClient; string connStr = "server=localhost;user=root;database=mydb;password=abc123"; string query = "SELECT * FROM customers"; using MySqlConnection conn = new MySqlConnection(connStr); conn.Open(); using MySqlCommand cmd = new MySqlCommand(query, conn); using MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine($"{reader["id"]} {reader["name"]} {reader["email"]}"); }
using MySql.Data.MySqlClient; string connStr = "server=localhost;user=root;database=mydb;password=abc123"; string query = "INSERT INTO customers (name, email) VALUES (@name, @email)"; using MySqlConnection conn = new MySqlConnection(connStr); conn.Open(); using MySqlCommand cmd = new MySqlCommand(query, conn); cmd.Parameters.AddWithValue("@name", "John"); cmd.Parameters.AddWithValue("@email", "[email protected]"); int rowsAffected = cmd.ExecuteNonQuery(); Console.WriteLine($"{rowsAffected} row(s) inserted.");This example shows how to execute an insert query with parameters using MySqlConnection and MySqlCommand objects. The query inserts a new row into the "customers" table with the name "John" and email "[email protected]". The number of rows affected is printed to the console. Overall, MySqlConnection Execute is used to execute MySQL queries in C# code. The examples show how to use parameters to safely insert data and how to read data from a select query. The package library used is MySql.Data.MySqlClient.