c# 读取mysql 表中数据
时间: 2023-08-11 21:28:32 浏览: 208
可以使用 MySQL Connector/NET 驱动程序来实现 C# 读取 MySQL 表中数据的操作。以下是一个示例代码:
```csharp
using System;
using MySql.Data.MySqlClient;
namespace ReadMySQLData
{
class Program
{
static void Main(string[] args)
{
string connectionString = "server=localhost;user=root;database=mydatabase;port=3306;password=mypassword;";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
connection.Open();
string query = "SELECT * FROM mytable";
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32("id");
string name = reader.GetString("name");
int age = reader.GetInt32("age");
Console.WriteLine("ID: {0}, Name: {1}, Age: {2}", id, name, age);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
Console.ReadKey();
}
}
}
```
在这个示例代码中,我们首先创建了一个 MySqlConnection 对象连接到 MySQL 数据库。然后使用 MySqlCommand 对象执行一个 SELECT 查询,并使用 MySqlDataReader 对象读取查询结果。最后,我们关闭了连接并显示了结果。
你需要根据你的实际情况修改 connectionString、query 和字段名等参数。
阅读全文
相关推荐















