gpt4 book ai didi

c# - 将查询结果写入文件

转载 作者:行者123 更新时间:2023-12-03 23:10:21 24 4
gpt4 key购买 nike

将查询结果写入文件时遇到问题。

string file = @"C:\Users\jakub\Desktop\plik.pdk";
FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite);

string connection = "DSN=PervasiveData;Database=BAZA1";
string query1 = "SELECT skrot FROM KONTRAHENCI WHERE id = 32";

OdbcConnection MyConn = new OdbcConnection(connection);
OdbcCommand MyCommand = new OdbcCommand(query1, MyConn);

现在我必须写信来归档我的查询结果。

我该怎么做?

最佳答案

始终在 Streams 中使用“using”指令,以确保自动释放资源

string file = @"C:\Users\jakub\Desktop\plik.pdk";
using (StreamWriter outputFile = new StreamWriter(file, true)) {

string connection = "DSN=PervasiveData;Database=BAZA1";
string query1 = "SELECT skrot FROM KONTRAHENCI WHERE id = 32";
OdbcCommand myCommand = new OdbcCommand(query1, myConn);

//Execute command and write output to file
outputFile.WriteLine(myCommand.ExecuteScalar().ToString());
}

您将需要一个事件连接(myconn)才能工作(取决于您是否使用 ms sql server oracle 等)。您也应该在这里使用“使用”。 Oracle 的一个简单解决方案是:

string yourConnectionString = "DSN=PervasiveData;Database=BAZA1"; // something similar

using (var conn = new OracleConnection(yourConnectionString )) {
conn.open()
var myCommand= conn.CreateCommand();
myCommand.CommandText = "SELECT skrot FROM KONTRAHENCI WHERE id = 32";

string file = @"C:\Users\jakub\Desktop\plik.pdk";
using (StreamWriter outputFile = new StreamWriter(file, true)) {
//Execute command and write output to file
outputFile.WriteLine(myCommand.ExecuteScalar().ToString());
}

关于c# - 将查询结果写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37787278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com