将查询结果写入文件

时间:2016-06-13 10:24:34

标签: 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);

现在我必须写入我的查询结果。

我该怎么做?

2 个答案:

答案 0 :(得分:4)

始终使用"使用" Streams指令确保自动释放资源

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());
  }

答案 1 :(得分:1)

总结一切:

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());
}