C# 在dataview可以直接增删改查mysql数据库
首先,确保你的项目中已经安装了MySql.Data。你可以通过NuGet包管理器安装它:
python
Install-Package MySql.Data -Version 8.0.28
csharp
using System;
using System.Data;
using MySql.Data.MySqlClient;
public class MySQLDataAccess
{
private string connectionString = "server=localhost;user=root;database=mydb;port=3306;password=mypassword";
public void Insert(string query)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.ExecuteNonQuery();
}
}
}
public DataTable Select(string query)
{
DataTable dataTable = new DataTable();
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
conn.Open();
adapter.Fill(dataTable);
}
}
return dataTable;
}
public void Update(string query)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.ExecuteNonQuery();
}
}
}
public void Delete(string query)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.ExecuteNonQuery();
}
}
}
}
// 使用示例
MySQLDataAccess db = new MySQLDataAccess();
// 插入
string insertQuery = "INSERT INTO mytable (column1, column2) VALUES ('value1', 'value2')";
db.Insert(insertQuery);
// 查询
string selectQuery = "SELECT * FROM mytable";
DataTable table = db.Select(selectQuery);
// 更新
string updateQuery = "UPDATE mytable SET column1 = 'newvalue' WHERE id = 1";
db.Update(updateQuery);
// 删除
string deleteQuery = "DELETE FROM mytable WHERE id = 1";
db.Delete(deleteQuery);