C#如何访问MYSQL数据库
时间: 2023-07-27 08:11:51 浏览: 61
C#可以通过使用MySQL Connector/NET提供的API来访问MySQL数据库。下面是一个简单的示例代码:
1. 首先,需要在项目中添加对MySQL Connector/NET的引用。
2. 然后,可以使用以下代码连接到MySQL数据库:
```csharp
using MySql.Data.MySqlClient;
string connectionString = "server=localhost;user id=root;password=yourpassword;database=yourdatabase";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
```
其中,`server`表示MySQL服务器地址,`user id`表示用户名,`password`表示密码,`database`表示要连接的数据库名称。
3. 连接成功后,可以执行SQL语句并获取数据:
```csharp
string sql = "SELECT * FROM yourtable";
MySqlCommand command = new MySqlCommand(sql, connection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["column1"].ToString());
Console.WriteLine(reader["column2"].ToString());
// ...
}
reader.Close();
```
其中,`yourtable`为要查询的表名,`column1`、`column2`等为要查询的列名。
4. 最后,记得关闭连接:
```csharp
connection.Close();
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)