winform连接MySQL数据库帮助类
时间: 2023-07-26 12:38:57 浏览: 107
winform连接数据库
以下是一个简单的 Winform 连接 MySQL 数据库的帮助类示例。需要先引用 `MySql.Data` 和 `MySql.Data.Types` 两个库。
```csharp
using MySql.Data.MySqlClient;
public class MySQLHelper
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
// 构造函数
public MySQLHelper()
{
Initialize();
}
// 初始化连接字符串
private void Initialize()
{
server = "localhost";
database = "mydatabase";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
// 打开连接
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
// 处理异常
return false;
}
}
// 关闭连接
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
// 处理异常
return false;
}
}
// 执行 SQL 命令,返回影响的行数
public int ExecuteNonQuery(string query)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
int rowsAffected = cmd.ExecuteNonQuery();
this.CloseConnection();
return rowsAffected;
}
else
{
return -1;
}
}
// 执行 SQL 查询,返回一个 MySqlDataReader 对象
public MySqlDataReader ExecuteReader(string query)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
return dataReader;
}
else
{
return null;
}
}
// 执行 SQL 查询,返回一个 DataTable 对象
public DataTable ExecuteQuery(string query)
{
DataTable dataTable = new DataTable();
try
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dataTable);
}
}
catch (MySqlException ex)
{
// 处理异常
}
finally
{
this.CloseConnection();
}
return dataTable;
}
}
```
使用方法:
```csharp
MySQLHelper mysql = new MySQLHelper();
string query = "SELECT * FROM mytable";
DataTable dataTable = mysql.ExecuteQuery(query);
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["id"] + " " + row["name"]);
}
```
其中 `ExecuteNonQuery()` 方法用于执行 INSERT、UPDATE 和 DELETE 命令,返回影响的行数;`ExecuteReader()` 方法用于执行 SELECT 命令,返回一个 MySqlDataReader 对象;`ExecuteQuery()` 方法用于执行 SELECT 命令,返回一个 DataTable 对象。需要根据具体情况选择合适的方法。
阅读全文