MySQLHelper 是一个用于操作 MySQL 数据库的 C# 库,它提供了一系列静态方法来执行常见的数据库操作,如创建、读取、更新和删除数据。要使用 MySQLHelper,首先需要安装它。你可以通过 NuGet 包管理器来安装:
安装完成后,你可以在项目中引入 MySql.Data.MySqlClient
命名空间并使用 MySQLHelper 类。以下是一些基本示例:
在你的项目的 appsettings.json
文件中添加一个连接字符串,例如:
{
"ConnectionStrings": {
"MyConnectionString": "server=localhost;port=3306;database=mydb;uid=myuser;password=mypassword"
}
}
using MySql.Data.MySqlClient;
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
// 在这里执行数据库操作
}
using MySql.Data.MySqlClient;
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM mytable";
using (MySqlCommand command = new MySqlCommand(query, connection))
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"ID: {reader["id"]}, Name: {reader["name"]}");
}
}
}
using MySql.Data.MySqlClient;
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO mytable (name) VALUES (@name)";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@name", "John Doe");
command.ExecuteNonQuery();
}
}
using MySql.Data.MySqlClient;
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "UPDATE mytable SET name = @name WHERE id = @id";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@name", "Jane Doe");
command.Parameters.AddWithValue("@id", 1);
command.ExecuteNonQuery();
}
}
using MySql.Data.MySqlClient;
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "DELETE FROM mytable WHERE id = @id";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@id", 1);
command.ExecuteNonQuery();
}
}
这些示例展示了如何使用 MySQLHelper 类执行基本的数据库操作。你可以根据自己的需求调整查询和参数。