发布:2024/3/26 23:13:09作者:管理员 来源:本站 浏览次数:541
using System;
using System.Data;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
public class MySqlHelper
{
private static string connectionString = "YourConnectionString";
public static async Task<int> ExecuteNonQueryAsync(string query)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var command = new MySqlCommand(query, connection))
{
await connection.OpenAsync();
return await command.ExecuteNonQueryAsync();
}
}
}
public static async Task<object> ExecuteScalarAsync(string query)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var command = new MySqlCommand(query, connection))
{
await connection.OpenAsync();
return await command.ExecuteScalarAsync();
}
}
}
public static async Task<DataTable> ExecuteDataTableAsync(string query)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var command = new MySqlCommand(query, connection))
{
using (var adapter = new MySqlDataAdapter(command))
{
var table = new DataTable();
await connection.OpenAsync();
await adapter.FillAsync(table);
return table;
}
}
}
}
public static async Task<MySqlDataReader> ExecuteReaderAsync(string query)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var command = new MySqlCommand(query, connection))
{
await connection.OpenAsync();
return await command.ExecuteReaderAsync(CommandBehavior.CloseConnection);
}
}
}
}
这个示例提供了四个异步帮助方法来执行MySQL数据库操作。这些方法使用了MySql.Data.MySqlClient库中的异步方法,如OpenAsync和ExecuteNonQueryAsync。这些方法使用了using语句来确保连接和命令对象在使用后正确地被释放。
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4