C#中MySql帮助类
时间: 2023-08-03 22:40:10 浏览: 111
在C#中使用MySql数据库可以使用MySql.Data.MySqlClient命名空间中提供的类来实现,这些类可以通过ADO.NET来访问数据库。但是,为了方便使用,我们可以封装一个帮助类来进行数据库操作,以下是一个简单的MySql帮助类的示例代码:
```
using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
namespace MySqlHelper
{
public class MySqlHelper
{
private string connectionString;
public MySqlHelper(string connectionString)
{
this.connectionString = connectionString;
}
public List<string> ExecuteQuery(string query)
{
List<string> results = new List<string>();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand(query, connection))
{
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
results.Add(reader.GetString(0));
}
}
}
}
return results;
}
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;
}
}
}
```
这个帮助类包含了两个方法:ExecuteQuery和ExecuteNonQuery。ExecuteQuery方法用于执行查询语句并返回结果集,ExecuteNonQuery方法用于执行不返回结果集的语句,例如插入、更新和删除语句。
使用示例:
```
using System;
using MySqlHelper;
namespace Test
{
class Program
{
static void Main(string[] args)
{
string connectionString = "server=localhost;database=mydb;uid=myuser;password=mypass;";
MySqlHelper helper = new MySqlHelper(connectionString);
// 查询
string query = "SELECT name FROM users;";
var results = helper.ExecuteQuery(query);
foreach (var result in results)
{
Console.WriteLine(result);
}
// 插入
string insertQuery = "INSERT INTO users (name, age) VALUES ('John', 30);";
int rowsAffected = helper.ExecuteNonQuery(insertQuery);
Console.WriteLine(rowsAffected + " rows affected.");
}
}
}
```
阅读全文