在C#中使用MySQLHelper来操作数据库,通常需要安装MySQL.Data包,然后创建一个MySQLHelper类来封装常用的数据库操作方法,包括连接数据库、执行查询、执行非查询操作等。
以下是一个示例代码,展示了如何使用MySQLHelper类来连接MySQL数据库并执行查询操作:
using MySql.Data.MySqlClient;
using System;
using System.Data;
public class MySQLHelper
{
private string connectionString;
public MySQLHelper(string connectionString)
{
this.connectionString = connectionString;
}
public DataTable ExecuteQuery(string query)
{
DataTable dataTable = new DataTable();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand(query, connection))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(command))
{
adapter.Fill(dataTable);
}
}
}
return dataTable;
}
public int ExecuteNonQuery(string query)
{
int rowsAffected = 0;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand(query, connection))
{
rowsAffected = command.ExecuteNonQuery();
}
}
return rowsAffected;
}
}
// 使用MySQLHelper类
string connectionString = "Server=localhost;Database=mydatabase;Uid=username;Pwd=password;";
MySQLHelper mySQLHelper = new MySQLHelper(connectionString);
// 执行查询操作
string query = "SELECT * FROM mytable";
DataTable dataTable = mySQLHelper.ExecuteQuery(query);
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["column1"].ToString());
}
// 执行非查询操作
string insertQuery = "INSERT INTO mytable (column1, column2) VALUES ('value1', 'value2')";
int rowsAffected = mySQLHelper.ExecuteNonQuery(insertQuery);
Console.WriteLine("Rows affected: " + rowsAffected);
通过这样封装的MySQLHelper类,可以方便地在C#中连接MySQL数据库并执行各种数据库操作。在实际应用中,还可以根据需求进一步扩展MySQLHelper类,添加更多的数据库操作方法。