在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類,添加更多的數據庫操作方法。