bengosha bengosha - 5 months ago 7
SQL Question

Writing query results into a file

I've problem when I write the result of a query 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);


And now I must write to file my result of query.

How can I do this?

Answer

Always use the "using" directive with Streams to ensure automatic release of the ressource

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