简体   繁体   中英

OrmLite (ServiceStack): Only use temporary db-connections (use 'using'?)

For the last 10+ years or so, I have always opened a connection the database (mysql) and kept it open, until the application closed. All queries was executed on the connection.

Now, when I see examples on Servicestack webpage, i always see the using -block being used, like:

using (var db = dbFactory.Open())
{
    if (db.CreateTableIfNotExists<Poco>())
    {
        db.Insert(new Poco { Id = 1, Name = "Seed Data"});
    }

    var result = db.SingleById<Poco>(1);
    result.PrintDump(); //= {Id: 1, Name:Seed Data}
}

In my current test-project, I got OrmLite to work in my normal way (one db-connection, no using-statements), so I basically had a class-wide _db , like this:

_dbFactory = new OrmLiteConnectionFactory($"Uid={dbAccount.Username};Password={dbAccount.Password};Server={dbAccount.Address};Port={dbAccount.Port};Database={dbAccount.Database}", MySqlDialect.Provider);

_db = _dbFactory.Open(); // var kept in memory, and used for all queries

It worked in the beginning, but now I suddenly got the Exception:

There is already an open DataReader associated with this Connection which must be closed first

Some code might run a SELECT here and there, and if I understand it correctly, if a SELECT and an INSERT would occur at the same time, this error appears?

If so, is it best-practice to always open a new connection for every single query (say, inside a using-statement)? Isnt that a big overhead, to do what for every query?

Having 1 DB Connection is not ThreadSafe so holding on to the connection is only an option if there's at most 1 thread accessing the DB connection.

Most ADO.NET providers enable connection pooling by default so it's more efficient to close the connection when you're done with it as the connection gets returned back to the pool which reduces the number of active connections in use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM