0

How to close all database connections in SQLite-WinRT wrapper. I need to delete the sqlite database but it is throwing exception Access is denied while deleting since some connection is already using database. So I need to close all the connections before deleting.

I have tried disposing database like:

var dbFile = await StorageFile.GetFileFromPathAsync(dbPath);
db = new SQLiteWinRT.Database(dbFile); 
db.Dispose();

But it doesn't work and throws the same exception.

Thanks!

Kishor Bikram Oli
  • 1,748
  • 1
  • 22
  • 40

3 Answers3

1

Perform your DB oriented operations within using {...} block.

The using statement obtains one or more resources, executes a statement, and then disposes of the resource.

Example:

using (var db = new SQLiteConnection(DbPath))
{
    db.Trace = true;
    db.Execute("DELETE FROM Person WHERE Id = ?", person.Id);
}
Muhammad Hassan
  • 1,037
  • 1
  • 8
  • 22
  • Hi M. Hassan, Thanks for your answer. There are lot of DB operations in different parts and passing the DbPath as parameter and creating new instance every time within `using{ . . .}` block doesn't seem to be feasible to me. Are there any options you can think of? – Kishor Bikram Oli Mar 03 '16 at 11:42
  • Was afraid of that case. You'd need to make changes one way or other. Connection pooling might help. – Muhammad Hassan Mar 03 '16 at 14:55
1

Sometimes SQLite doesn't dispose correctly. To get around this you can call Collect on the garbage collector.

Example

var dbFile = await StorageFile.GetFileFromPathAsync(dbPath);
db = new SQLiteWinRT.Database(dbFile); 
db.Dispose();

// Then force GC
GC.Collect();

If this doesn't work for you see this SO question for some alternative solutions.

Community
  • 1
  • 1
Colin Bacon
  • 15,436
  • 7
  • 52
  • 72
1

I had the same problem. In my case I had not disposed of prepared statements correctly. Every time you call PrepareStatementAsync you have to call Dispose on the resulting statement (or use using).

sast
  • 478
  • 4
  • 8