NOTE: This is not a duplicate of What does SqlCommand.Prepare() do and when should it be used? or SQLite/C# Connection Pooling and Prepared Statement Confusion or other stack overflow questions. I am not asking whether prepared statements are appropriate for my use case. I am asking how to use them together with IDisposable. END NOTE
I have a c# program that uses about 100 SQL statements. I am creating a SQLiteCommand inside a using
block each time I need it:
string query = @"select ... ";
using (SQLiteCommand cmd = new SQLiteCommand(query, conn))
{
cmd.Parameters.Add(new SQLiteParameter( ... ));
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read()) {
...
}
}
}
I would like to improve performance by using prepared statements, so that each statement is compile once and used repeatedly thoughout the lifetime of the program.
My dilemma is that DbCommand implements I Disposable, and every example I see shows the command being disposed as soon as the SQL statement is executed.
Is it OK to not dispose of DbCommand after executing a SQL statement? What side effects would that have? Alternatively, if I do dispose of the command, how do I achieve the "compile once execute multiple times" flow.