c#mysql表格另存为
时间: 2023-10-16 21:12:43 浏览: 39
你可以使用以下代码将 MySQL 数据库中的表格另存为:
```csharp
using System;
using MySql.Data.MySqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "server=yourServerAddress;port=yourPortNumber;database=yourDatabaseName;user=yourUserName;password=yourPassword";
string tableName = "yourTableName";
string filePath = "yourFilePath";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM " + tableName, connection);
MySqlDataReader reader = command.ExecuteReader();
// Save data to file
using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))
{
// Write column names
for (int i = 0; i < reader.FieldCount; i++)
{
file.Write(reader.GetName(i));
if (i < reader.FieldCount - 1) file.Write(",");
}
file.WriteLine();
// Write row data
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (!reader.IsDBNull(i))
{
string value = reader[i].ToString();
value = value.Replace(",", ""); // Remove commas from values
file.Write(value);
}
if (i < reader.FieldCount - 1) file.Write(",");
}
file.WriteLine();
}
}
reader.Close();
connection.Close();
}
}
}
```
你需要将 `connectionString` 更改为你的 MySQL 服务器连接字符串,将 `tableName` 更改为你要保存的表格的名称,将 `filePath` 更改为你要保存到的文件路径。此代码将表格中的所有行保存为 CSV 文件。