How to Close Sqlite Connection without explicitly calling Close Method using .NET How to Close Sqlite Connection without explicitly calling Close Method using .NET sqlite sqlite

How to Close Sqlite Connection without explicitly calling Close Method using .NET


Keeping the connection open for the lifetime of your application is not a good way to go.
I suggest to not follow this route.
On the contrary, I will try to encapsulate the functionality to attach a database inside a method that could be called on the need to use basis.

For example:

private static void AttachDB(string fileDB, string aliasName, SQLiteConnection cn) {     string sqlText = string.Format("ATTACH '{0}' AS {1}", fileDB, aliasName)     SQLiteCommand cmd = new SQLiteCommand(sqlText, cn)     cmd.ExecuteNonQuery(); } 

then in your code

using(SQLiteConnection cn = new SQLiteConnection(GetConnectionString())){     AttachDB(@"C:\SQLite\UserData.sqlite3", "UserData", cn);     // Do your code here} 


Close should not disconnect your database but this will only work when .NET connection pooling mechanism is on. Make sure you have that enabled in your connection string:

Data Source=filename;Version=3;Pooling=True;Max Pool Size=100;


Depending on how your class is defined, you can use Dispose or a destructor. Or, explicitly call Close() at the end of the program (from within Main, after Run...).