Checking if Table Exists Keeping Connection Open in SQLite
So I have a method which is supposed to check if a table exists in a database which is defined as follows:
internal override bool TableExists(string tableName)
{
bool tableExists = false;
// Check the Tables schema and see if the table exists
using (SQLiteConnection conn = (SQLiteConnection) CreateConnection())
{
conn.Open();
DataRow[] rows = conn.GetSchema("Tables").Select(string.Format("Table_Name = '{0}'", tableName));
tableExists = (rows.Length > 0);
}
// Actually called elsewhere in the code, just here for testing.
File.Delete(DatabaseEnvironmentInfo.GetPrimaryDataFile(DatabaseName));
return tableExists;
}
CreateConnection()
just creates a new connection with a connection string so I don't think the issue is there. If I have remove the line conn.GetSchema("Tables")...
and I am able to delete the database file but if I add that line back in I get the following exception when I try to delete after the using
:
System.IO.IOExcep开发者_高级运维tion: The process cannot access the file 'C:\db.sqlite' because it is being used by another process..
Do DataRow
objects keep a connection to the database or does anyone know what the issue could be? If there is a better way to check if a table exists in SQLite I am open to that as well.
Thanks!
Ok so I've figured out the issue so I'll post it here in case anyone comes across the same problem. Basically I had connection pooling enabled so the connections were maintaining an open connection with the database and that was why i was seeing the exception. Just add the following after the using
:
SQLiteConnection.ClearAllPools();
If you add conn.Close() at the end of your using, can you delete your database ?
I've had a similar problem without using connection pooling. I've found that the problem was caused by the missing disposal of SQLiteCommand
s in the TableAdapters.
You can find additional details here .
精彩评论