I have to run different sql statement in one connection may be 5-6. Example:
- Checking some condition in a table.
- Updating another table on the basis of value received from first command.
- Inserting new data to some other table on the basis of result of first command.
All of the command contains parameterized query.
This is how I am approaching to it. Is is good approach? Does this create multiple round trips to database? Or am I wrong on round trips. Please suggest me on this.
using (NpgsqlConnection connection = new NpgsqlConnection (connectionString))
{
connection.Open();
using (NpgsqlCommand command1 = new NpgsqlCommand (commandText1, connection))
{
//select
}
using (NpgsqlCommand command2 = new NpgsqlCommand (commandText2, connection))
{
//update
}
// etc
}
NpgsqlConnectionis well-behaved, your example code will, in fact, runncommands using one connection to the DB. However, I second @Igor's comment that you consider converting this logic into a stored procedure.