Do I have to Dispose the SQLiteCommand objects?
Asked Answered
E

4

7

How do I treat the SQLiteCommand object, do I have to call Dispose() after ExecuteScalar, ExecuteNonQuery and ExecuteReader or not?

The documentation example on SQLiteCommand doesn't dispose it whilst in the SQLiteTransaction the example disposes the SQLiteCommand object.

I always close the data reader object though. My application accesses the db from many threads.

Mostly I am interested in not leaking connections or disturbing SQLite. I am aware of using and IDisposable usage

Earthling answered 14/3, 2013 at 11:39 Comment(1)
Rule of thumb: if it's disposable, dispose it when you no longer need it.Saboteur
E
11

It's best-practise to dispose everything that implements IDisposable as soon as you're finished with it because it might use unmanaged resources.

This should be done with the using-statement since it wraps the code that uses this object and because it disposes it also in case of an exception.

using(var con = new SQLiteConnection(conString))
using(var cmd = new SQLiteCommand(con))
{
    con.Open();
    // ...
} // also closes the connection
Encephalitis answered 14/3, 2013 at 11:41 Comment(2)
how can i use Connection and Command in two different methods? getting disposed exception.Uninterested
You should ask a question and provide the code and all relevant informationEncephalitis
P
2

If it is disposable, dispose it if you will not use it again. The best would be, to use using

using(SQLiteCommand cmd as new SQLiteCoammand())
{
   ...
}

So it will be disposed automatically when leaving the using scope.

Petrifaction answered 14/3, 2013 at 11:43 Comment(0)
K
1

Just do this:

using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
using(var command = connection.CreateCommand())
{
   command.CommandText = "...";
   connection.Open();
   command.ExecuteNonQuery();
}

Not calling dispose on the command won't do anything too bad. However calling Dispose on it will supress the call to the finalizer, making calling dispose a performance enhancement.

Kellam answered 14/3, 2013 at 11:41 Comment(1)
It seems that it does actually do something bad. Although I am not really sure why. Just refactoring my DAOs and expect the issue to go away (I hate this kind of magic but in this case I don't want to dig into SQLite source)Earthling
M
1

The using statement will call Dispose on an object even if an exception occurs that bypasses the code that calls Close(). This way you don't have to write a try/finally block just to close the readers or the connection. You also avoid this 1-in-100 case where you forget to write the proper finally block.

Such 1-in-100 cases have a tendency to occur much more frequently than one would think

Makedamakefast answered 14/3, 2013 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.