In recent weeks I became very concerned that the way I've been working with database connections for the past years, is simply wrong.
I exclusively create a new connection for each database operation I have to perform. only in the more complex programs, I would stack several tasks (Sql commands) in the background and then every few seconds I would create a new single connection, and execute these with the same connection.
Here is typical sample:
SqlConnection connection = new SqlConnection(con);
SqlCommand command = new SqlCommand(@"
DECLARE @Pk TABLE (Id int)
INSERT INTO Petrol.Reports(
[TimeStamp])
OUTPUT INSERTED.Id INTO @Pk
VALUES(
@TimeStamp)
SELECT Id FROM @Pk", connection);
command.CommandType = CommandType.Text;
SqlParameter parameter = command.Parameters.Add("@TimeStamp", SqlDbType.DateTime);
parameter.Value = this.TimeStamp;
using (connection)
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
this.Id = reader.GetInt32(0);
Ref.Petrol_ReportsById[Id] = this;
}
}
}
Recently I started working with PostgreSQL and I was freighted to see that it creates a new process for almost every connection I create.
The deal is that most code samples around are using very similar approach, but I'm afraid that this is just to keep things simple.
I consider re writing my objects generating tool to share a single connection between all operations (with thread safety in mind), would this be a correct approach in your opinion?