发布:2024/3/25 10:10:40作者:管理员 来源:本站 浏览次数:467
在C#中使用MySQL进行增删改查操作,并使用异步编程,你可以使用MySql.Data库。以下是一个简单的例子:
首先,确保安装了MySql.Data库。通过NuGet安装:
Install-Package MySql.Data -Version 8.0.28
然后,使用以下代码进行异步的增删改查操作:
using System;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
public class MySqlAsyncCRUDExample
{
private static readonly string connectionString = "server=localhost;user=root;database=mydb;port=3306;password=mypassword";
public static async Task Main(string[] args)
{
using (var connection = new MySqlConnection(connectionString))
{
await connection.OpenAsync();
// 插入
var insertCommand = "INSERT INTO mytable (column1, column2) VALUES (?, ?);";
using (var insertCmd = new MySqlCommand(insertCommand, connection))
{
insertCmd.Parameters.AddWithValue("?column1", "value1");
insertCmd.Parameters.AddWithValue("?column2", "value2");
await insertCmd.ExecuteNonQueryAsync();
}
// 查询
var selectCommand = "SELECT * FROM mytable;";
using (var selectCmd = new MySqlCommand(selectCommand, connection))
{
using (var reader = await selectCmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
Console.WriteLine($"{reader["column1"]}, {reader["column2"]}");
}
}
}
// 更新
var updateCommand = "UPDATE mytable SET column1 = ? WHERE id = ?;";
using (var updateCmd = new MySqlCommand(updateCommand, connection))
{
updateCmd.Parameters.AddWithValue("?column1", "newValue");
updateCmd.Parameters.AddWithValue("?id", 1);
await updateCmd.ExecuteNonQueryAsync();
}
// 删除
var deleteCommand = "DELETE FROM mytable WHERE id = ?;";
using (var deleteCmd = new MySqlCommand(deleteCommand, connection))
{
deleteCmd.Parameters.AddWithValue("?id", 1);
await deleteCmd.ExecuteNonQueryAsync();
}
}
}
}
确保替换连接字符串中的服务器、用户、数据库、端口和密码为你的实际信息,并且根据你的MySQL表结构调整SQL语句。
以上代码展示了如何在C#中使用异步方式进行MySQL数据库的增删改查操作。使用OpenAsync(), ExecuteNonQueryAsync(), 和 ExecuteReaderAsync() 方法,可以避免阻塞主线程,提高程序的响应性。
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4