将查询结果写入文件

Writing query results into a file

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

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 服务器 oracle 等)。你也应该在这里使用 "using" 。一个简单的 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());
  }

总结一切:

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";

     OdbcConnection MyConn = new OdbcConnection(connection);

     MyConn.Open();

     OdbcCommand myCommand = new OdbcCommand(query1, myConn);

     var result = myCommand.ExecuteScalar();

     //Execute command and write output to file
     if((result !=null) && (result != DBNull.Value))
          outputFile.WriteLine(result.ToString());
}