Search code examples
c#sqlitefreeze

sqlite database is locked on insertion


There's a simple code

var insert = 
    @"INSERT INTO [files] (
     [Name],
     [FullName],
     [MD5])
     VALUES (@Name, @FullName, @MD5);";
using (var con = _db.OpenConnection())
{
    using (var cmd = con.CreateCommand())
    {
        cmd.CommandText = insert;
        cmd.Parameters.AddWithValue("@Name", item.Name);
        cmd.Parameters.AddWithValue("@FullName", item.FullName);
        cmd.Parameters.AddWithValue("@MD5", item.MD5);
        cmd.ExecuteNonQuery();
    }
 }

applications hangs for some time when executing

cmd.ExecuteNonQuery();

and then fails with exception "database is locked". Why this is happening? Application is not multithreaded. DB file is just-created.


Solution

  • Problem solved. Before this code there was call to SqlCommand.ExecuteReader(). Though connection and command which created this reader were disposed, this reader itself wasn't disposed. After fixing with "using(reader)" connection was closed properly and error above disappeared.

    In total: DataReader can still hold a connection even if connection and SqlCommand were disposed explicitly.