Matt Butler

Matt Butler

  • NA
  • 18
  • 0

Exporting from SQL

Nov 3 2010 11:10 AM
I am trying to export from my SQL server. I have the connection working perfectly, but I am receiving an error when I export dates/GUIDs/etc.

The error says that it is not able to cast the object from datetime to string or from uniqueidentifier to string. Is there something that I am missing here, or should I not be using string at all? I am new to C# - I am a java convert. Please be nice. If you have questions, I will do my best to answer them. Below is the code that I have thus far.

Kind Regards

         /*
* Exports data to the CSV file.
*/

private void exportToCSVfile(string fileOut)
{
// Connects to the database, and makes the select command.
SqlConnection conn = new SqlConnection(prop.sqlConnString);
string sqlQuery = "select * from " + this.lbxTables.SelectedItem.ToString();
SqlCommand command = new SqlCommand(sqlQuery, conn);
conn.Open();

// Creates a SqlDataReader instance to read data from the table.
SqlDataReader dr = command.ExecuteReader();

// Retrives the schema of the table.
DataTable dtSchema = dr.GetSchemaTable();

// Creates the CSV file as a stream, using the given encoding.
StreamWriter sw = new StreamWriter(fileOut, false, this.encodingCSV);

string strRow; // represents a full row

// Writes the column headers if the user previously asked that.
if (this.chkFirstRowColumnNames.Checked)
{
sw.WriteLine(columnNames(dtSchema, this.separator));
}

// Reads the rows one by one from the SqlDataReader
// transfers them to a string with the given separator character and
// writes it to the file.
try
{
while (dr.Read())
{
strRow = "";
for (int i = 0; i < dr.FieldCount; i++)
{
strRow += dr.GetString(i);
if (i < dr.FieldCount - 1)
{
strRow += this.separator;
}
}
sw.WriteLine(strRow);
}
}
catch (Exception)
{
MessageBox.Show("Error encountered! File creation halted.","Fatal Error!");
}



// Closes the text stream and the database connenction.
sw.Close();
conn.Close();

// Notifies the user.
MessageBox.Show("Done!");
}


Answers (8)