I'm writing some console applications to move some data between SQLite databases. The classes for the connection and various prepared statements implenent IDisposable, so I'm instantiating these objects using using
blocks, like this:
using (SQLiteConnection sqlite_conn = new SQLiteConnection(connectionString))
{
sqlite_conn.Open();
using (SQLiteCommand sqlite_cmd = new SQLiteCommand())
{
sqlite_cmd.Connection = sqlite_conn;
sqlite_cmd.CommandText = "INSERT INTO SOMETHING SOMETHING;";
sqlite_cmd.ExecuteNonQuery();
}
sqlite_conn.Close();
}
But, I need to be able to create these connections in one method, and then call them in other methods. What is the cleanest and least confusing way for me to store these connections as instance variables? I want to make sure their .Dispose()
methods are called in an intelligent way, but can't see a good way to make sure all of the action occurs within the context of a single using
block.
I realize this is a C# newb question so please tailor your answers as such. If you have a suggested solution, I'd love it if you included a code sample to illustrate.
EDIT: My use case is a console app. Someone passes in the source and destination connection strings, and the console app performs an operation. Would I actually make my console class Program itself implement IDisposable like this?:
class Program : IDisposable
{
private SQLiteConnection sourceConnection;
private SQLiteConnection destinationConnection;
public void Dispose()
{
sourceConnection.Dispose();
destinationConnection.Dispose();
}
}