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

标签 c# sql odbc

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

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/

相关文章:

c# - 私有(private)类成员中关键字 'this' 的正确用法是什么?

SQL Server : return column names based on a record's value

c# - ApiControllers 和 Razor View

mysql - 从 group by 和 unique 获得不同的结果

php - 使用sql检查特定时间的餐厅表可用性

php - 允许的内存大小为 134217728 字节耗尽(尝试分配 18063885380364533825 字节)

MySQL仅在给出完整号码时才匹配区号

postgresql - 如何通过 ODBC 在 Access 中获取详细的 PostgreSQL 错误?

c# - 检测设备是用作笔记本电脑还是平板电脑

c# - WebApi 和 MVC 之间的共享模型