C sharp读取.DB文件的所有值,转换成txt文件
时间: 2024-05-08 15:16:03 浏览: 10
以下是一个示例代码,可以读取一个名为“database.db”的SQLite数据库文件,并将其所有值转换为一个名为“output.txt”的文本文件。
```csharp
using System;
using System.Data.SQLite;
using System.IO;
namespace DBtoTXT
{
class Program
{
static void Main(string[] args)
{
//设置数据库文件路径
string dbFilePath = @"C:\database.db";
//设置输出文件路径
string outputFilePath = @"C:\output.txt";
//创建SQLite连接
SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbFilePath + ";Version=3;");
try
{
//打开连接
connection.Open();
//创建命令对象
SQLiteCommand command = new SQLiteCommand("SELECT * FROM table_name", connection);
//执行查询
SQLiteDataReader reader = command.ExecuteReader();
//创建输出流
StreamWriter writer = new StreamWriter(outputFilePath);
//遍历结果集
while (reader.Read())
{
//遍历每一列
for (int i = 0; i < reader.FieldCount; i++)
{
//将列值写入输出流
writer.Write(reader[i].ToString() + "\t");
}
//写入换行符
writer.WriteLine();
}
//关闭输出流
writer.Close();
//关闭结果集
reader.Close();
}
catch (Exception ex)
{
//处理异常
Console.WriteLine(ex.Message);
}
finally
{
//关闭连接
connection.Close();
}
}
}
}
```
在代码中,“table_name”应替换为要读取的表格的名称。输出文件将包含所有行和列的值,每个值之间用制表符分隔,每行之间用换行符分隔。