Checking if Table Exists Keeping Connection Open in SQLite
Asked Answered
P

3

0

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.IOException: The process cannot access the file 'C:\db.sqlite' because it is being used by another process..

Do DataRowobjects 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!

Proselyte answered 13/5, 2011 at 15:23 Comment(0)
P
2

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();
Proselyte answered 13/5, 2011 at 20:48 Comment(0)
S
0

If you add conn.Close() at the end of your using, can you delete your database ?

Senegal answered 13/5, 2011 at 15:26 Comment(3)
I have already tried that and it doesn't help. Plus I'm pretty sure the the using statement will explicitly close the connection when we exit scope.Proselyte
The using statement makes sure that dispose will be called and the object is registered for garbage collection when the block ends. I though that maybe the dispose had not been called yet when you try to delete the fileSenegal
Yeah I suppose that's possible. But in the real code I try to delete the database much further along in the code. This is just where I narrowed it down to.Proselyte
M
0

I've had a similar problem without using connection pooling. I've found that the problem was caused by the missing disposal of SQLiteCommands in the TableAdapters.

You can find additional details here .

Mitchelmitchell answered 1/10, 2012 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.