MySQL 是最熱門的關聯資料庫之一。目前DB-Engines將 MySQL 排名為全球第二熱門的資料庫。
引用 MySql.Data.MySqlClient
程式範例:
using MySql.Data.MySqlClient;
const string database = "mydatabase";
const string databaseServer = "localhost";
const string databaseUser = "root";
const string databasePassword = "mypassword";
string connectionString =
$"server={databaseServer};" + $"user={databaseUser};" +
$"password={databasePassword};" + $"database={database};" +
"charset=utf8;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open(); //資料庫連線
// 在這裡執行資料庫操作
connection.Close(); //資料庫斷線
}
假設mydatabase有一張users的表,表內有id(primary key). username. email
ExecuteReader
讀取資料:
MySqlDataReader reader = cmd.ExecuteReader();
MySqlDataReader
方法:
Read()
:GetInt32(columnName)
:GetString(columnName)
:using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string sql = "SELECT * FROM users";
using (MySqlCommand cmd = new MySqlCommand(sql, connection))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32("id");
string username = reader.GetString("username");
string email = reader.GetString("email");
Console.WriteLine($"ID: {id},
Username: {username}, Email: {email}");
}
}
}
}
程式範例:
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string insertSql =
"INSERT INTO users (username, email) VALUES (@username, @email)";
using (MySqlCommand insertCommand = new MySqlCommand(insertSql, connection))
{
insertCommand.Parameters.AddWithValue("@username", "john_doe");
insertCommand.Parameters.AddWithValue("@email", "john@example.com");
int rowsAffected = insertCommand.ExecuteNonQuery();
Console.WriteLine($"Inserted {rowsAffected} rows.");
}
}
程式範例:
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string updateSql =
"UPDATE users SET email = @newEmail WHERE username = @username";
using (MySqlCommand updateCommand = new MySqlCommand(updateSql, connection))
{
updateCommand.Parameters.AddWithValue("@newEmail", "new_email@example.com");
updateCommand.Parameters.AddWithValue("@username", "john_doe");
int rowsAffected = updateCommand.ExecuteNonQuery();
Console.WriteLine($"Updated {rowsAffected} rows.");
}
}
DELETE 操作將永久刪除資料,這邊需要特別注意
程式範例:
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string deleteSql =
"DELETE FROM users WHERE username = @username";
using (MySqlCommand deleteCommand = new MySqlCommand(deleteSql, connection))
{
deleteCommand.Parameters.AddWithValue("@username", "john_doe");
int rowsAffected = deleteCommand.ExecuteNonQuery();
Console.WriteLine($"Deleted {rowsAffected} rows.");
}
}
期望挑戰30天持續更新成功 ~ DAY19