C# 连接 MySQl
时间: 2023-11-22 22:37:09 浏览: 225
C# 连接Mysql
4星 · 用户满意度95%
C连接MySQL需要使用MySQL连接器,并且需要引用System.Data命名空间和MySql.Data.MySqlClient命名空间。下面是一个示例代码,展示了如何使用C#连接MySQL数据库:
```csharp
using System;
using System.Data;
using MySql.Data.MySqlClient;
public class MySQLConnector
{
private MySqlConnection connection;
public MySQLConnector(string connectionString)
{
connection = new MySqlConnection(connectionString);
}
public void Connect()
{
try
{
connection.Open();
Console.WriteLine("数据库连接成功!");
}
catch (Exception ex)
{
Console.WriteLine("数据库连接失败:" + ex.Message);
}
}
public void Disconnect()
{
connection.Close();
Console.WriteLine("数据库连接已断开!");
}
public DataTable SelectData(string tableName, string columns, string condition)
{
DataTable dataTable = new DataTable();
string sql = "";
if (string.IsNullOrEmpty(condition))
{
sql = "SELECT " + columns + " FROM " + tableName;
}
else
{
sql = "SELECT " + columns + " FROM " + tableName + " WHERE " + condition;
}
MySqlCommand command = new MySqlCommand(sql, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(dataTable);
return dataTable;
}
public int UpdateData(string tableName, string columnsAndValues, string condition)
{
string sql = "UPDATE " + tableName + " SET " + columnsAndValues + " WHERE " + condition;
MySqlCommand command = new MySqlCommand(sql, connection);
int rowsAffected = command.ExecuteNonQuery();
return rowsAffected;
}
}
```
以上代码展示了一个MySQL连接器的基本操作,包括连接数据库、断开连接、查询数据和修改数据。你可以根据自己的需求进行相应的修改和扩展。
阅读全文