views:

282

answers:

1

How can you execute multiple DbCommands with one connection?

Example:

var db = DatabaseFactory.CreateDatabase();
var dbCommand = db.GetSqlStringCommand(InsertCommandText);
...
db.ExecuteNonQuery(dbCommand);

Now, I want to be able to Execute multiple dbCommands. For instance in pseudo kind of code:

var db = DatabaseFactory.CreateDatabase();
var dbCommand1 = db.GetSqlStringCommand(InsertCommandText);
...
var dbCommand1 = db.GetSqlStringCommand(InsertCommandText);
...
Adding both commands to db
Executing them
+1  A: 

Each call to ExecuteNonQuery(DbCommand) will potentially use a new connection. If you wanted to ensure that you were always using the same connection you could use the overload ExecuteNonQuery(DbCommand, DbTransaction). If you pass in a transaction Enterprise Library will use the connection associated with the transaction. Of course, you may not want to use a transaction if it is not required.

Maybe it would help to know why you want to only use one connection?

Tuzo
I need to insert 750 records at once. I used open close connection for all 750 but it takes a long time. A batch insert also takes a long time. There are 350 concurrent users that will need to insert 750 records at the same time. So I need the fastest way!
Lieven Cardoen
How long did it take for 750 inserts? Was it for one user performing the 750 inserts or 350 concurrent? Do you have indexes on the tables? By default ADO.NET uses connection pooling [ http://msdn.microsoft.com/en-us/library/8xx3tyca ] so even though you are doing an open and close you should not be actually physically opening a connection to the database every time and is probably not the source of your performance issue (unless maxpoolsize is being reached but then I would expect to see timeout expired errors).
Tuzo

related questions