简体   繁体   中英

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.

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.

Be aware to click on Write changes on SQLite browser if it is running and there are any unsaved changes!

Sqlite 浏览器

In my case it was very stupid of me, I was making changes in SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post request worked as expected.
According to @Rohan Shenoy in this topic: SQLite Database Locked exception

Your code lacks the call to prepare()

int i=0;
        try
        {
            Conectar();
            SQLiteCommand comando = new SQLiteCommand(con);
            comando.CommandText = "INSERT INTO EMPRESA (NAME,ESTADO) VALUES (@name, @estado)";
            comando.Parameters.AddWithValue("@name", art.NAME);
            comando.Parameters.AddWithValue("@estado", art.ESTADO);
            comando.Prepare();
            con.Open();
            i = comando.ExecuteNonQuery();
            con.Close();
        }
        catch (SQLiteException ex)
        {
            string a = ex.Message.ToString();   
            throw;
        }

        return i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM