使用button将数据库中的表保存为txt 自行设置输出位置和名字
时间: 2024-04-17 13:24:20 浏览: 18
你可以使用 C# 中的 Windows Forms 应用程序和一个来实现将数据库中的表保存为 txt 文件,并自行设置输出位置和文件名。以下是一个示例代码:
```csharp
using System;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
namespace DatabaseToTxt
{
public partial class Form1 : Form
{
private string connectionString = "YourConnectionString"; // 替换为你的数据库连接字符串
public Form1()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
string tableName = txtTableName.Text.Trim(); // 获取文本框中的表名
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Text Files (*.txt)|*.txt";
saveFileDialog.FileName = "output.txt";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string outputPath = saveFileDialog.FileName;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = $"SELECT * FROM {tableName}";
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
using (StreamWriter writer = new StreamWriter(outputPath))
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
writer.Write(reader[i].ToString() + "\t");
}
writer.WriteLine();
}
}
}
}
}
MessageBox.Show("数据库内容已成功保存为文本文件。", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("保存文本文件时发生错误:" + ex.Message, "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
```
在上述代码中,你需要将 `YourConnectionString` 替换为你的数据库连接字符串。然后,创建一个 Windows Forms 应用程序,拖放一个按钮、一个文本框和一个 SaveFileDialog 控件到窗口上,并将按钮的 Click 事件与 `btnSave_Click` 方法关联。在 `btnSave_Click` 方法中,获取文本框中的表名,并弹出一个 SaveFileDialog 对话框,让用户选择输出的位置和文件名。然后执行查询并将结果保存到用户选择的文件中。最后,通过消息框显示保存成功或保存失败的提示信息。
这是一个可供参考的示例,你可以根据你的需求进行修改和扩展。