第一种:
using System;
using MySql.Data.MySqlClient;
class Program {
static void Main(string[] args) {
string connectionString = "server=127.0.0.1;database=database;uid=username;password=mypassword;";
using MySqlConnection connection = new MySqlConnection(connectionString);
try {
connection.Open();
Console.WriteLine("Connection Opened!");
string sqlQuery = "SELECT * FROM mytable";
using MySqlCommand command = new MySqlCommand(sqlQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
Console.WriteLine($"Column1: {reader[0]}, Column2: {reader[1]}");
}
} catch (Exception ex) {
Console.WriteLine("Error: " + ex.Message);
} finally {
connection.Close();
Console.WriteLine("Connection Closed!");
}
}
}
第二种:
using Microsoft.EntityFrameworkCore; public class MyDbContext : DbContext { public DbSet<Customer> Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySQL("server=localhost;user=root;database=mydatabase;password=mypassword;"); } } // 使用上下文进行数据库操作 using (var dbContext = new MyDbContext()) { // 查询所有客户 var customers = dbContext.Customers.ToList(); // ... }
第三种:
using MySql.Data.MySqlClient;
// ...
string connectionString = "server=localhost;user=root;database=mydatabase;password=mypassword;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
// 创建命令对象
var command = new MySqlCommand("SELECT * FROM customers", connection);
// 执行查询
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
// 处理每行数据
string name = reader.GetString("name");
int age = reader.GetInt32("age");
// ...
}
}
connection.Close();
}