tags:

views:

190

answers:

1

running sqlbulkcopy in c# and I get an error: WriteToServer: Connection property has not been initialized.

it happens at the WriteToServer command. The connection is open.

using (SqlBulkCopy s = new SqlBulkCopy(conn))
{
  foreach (DataTable dt in ds.Tables)
  {

    s.DestinationTableName = "tmp_" + dt.TableName;
    s.NotifyAfter = 5000;
    s.SqlRowsCopied += new SqlRowsCopiedEventHandler(s_SqlRowsCopied);
    s.WriteToServer(dt);
    s.Close();
  }
}

Correct Code:

using (SqlBulkCopy s = new SqlBulkCopy(conn))
{
  foreach (DataTable dt in ds.Tables)
  {
    s.DestinationTableName = "tmp_" + dt.TableName;
    s.NotifyAfter = 5000;
    s.SqlRowsCopied += new SqlRowsCopiedEventHandler(s_SqlRowsCopied);
    s.WriteToServer(dt);
  }
  s.Close();
}
+1  A: 

At a glance I would guess that the first pass through the foreach loop is executing correctly, then s.Close(); is cleaning up the SqlBulkCopy instance and clearing its Connection property, thus creating the exception on the second pass.

STW
In addition, there's no need to explicitly close it. The `s.Close()` call can be removed entirely since SqlBulkCopy implements `IDisposable`, therefore the existing `using` block will close and dispose of it.
Ahmad Mageed
I would leave it in, explicit closure is redundant--but it's good to have just in case that `using` block somehow goes away. Personally my preference is to leave the little optimizations up to the compiler (it's pretty spanky at those) and keep the code as readable and clear as possible
STW