写一个C#mysql工具类
时间: 2023-08-03 07:27:58 浏览: 141
MySQL工具类
以下是一个简单的 C# MySQL 工具类的实现,包含了连接、查询和关闭数据库等基本操作:
```csharp
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace MySqlUtils
{
public class MySqlHelper
{
private readonly string connectionString; // 数据库连接字符串
public MySqlHelper(string connectionString)
{
this.connectionString = connectionString;
}
// 执行查询,返回 DataTable
public DataTable ExecuteQuery(string sql)
{
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var command = new MySqlCommand(sql, connection);
var adapter = new MySqlDataAdapter(command);
var dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
// 执行非查询操作,返回受影响的行数
public int ExecuteNonQuery(string sql)
{
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var command = new MySqlCommand(sql, connection);
return command.ExecuteNonQuery();
}
}
// 关闭数据库连接
public void Close()
{
MySqlConnection.ClearAllPools(); // 清空连接池
}
}
}
```
使用示例:
```csharp
using System;
using System.Data;
using MySqlUtils;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var connectionString = "server=localhost;uid=root;pwd=root;database=test;";
var helper = new MySqlHelper(connectionString);
// 查询
var dataTable = helper.ExecuteQuery("SELECT * FROM users");
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["id"] + " " + row["name"]);
}
// 非查询操作
var affectedRows = helper.ExecuteNonQuery("INSERT INTO users(name) VALUES('Test')");
Console.WriteLine("Affected Rows: " + affectedRows);
helper.Close();
}
}
}
```
注意:该示例中的连接字符串需要根据实际情况进行修改。
阅读全文