Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Database is locked" with SQLite and C#

I have a problem with my code. I want to delete some rows in my SQLite database but I get a "Database is locked" exception. I read several posts about that like this post, but my problem is still here.

Here is my code :

using (var c = new SQLiteConnection(_connectionSQLite))
{
    c.Open();

    if (c.State == ConnectionState.Open)
    {
        var reqExist = string.Concat("SELECT id FROM ... ");
        using (var cmdExist = new SQLiteCommand(reqExist, c))
        {
            var reqUpdate = string.Concat("UPDATE ... WHERE id = ", cmdExist.ExecuteScalar());

            using (var cmdUpdate = new SQLiteCommand(reqUpdate, c))
            {
                cmdUpdate.ExecuteNonQuery();
            }
        }
    }

    c.Close();
}

I get the "database is locked" exception on the line cmdUpdate.ExecuteNonQuery();. I tried replace with a DELETE FROM, same result, but with a SELECT, it works, I really don't understand what's wrong with my code.

Thanks for any help.

like image 367
BlackAlpha Avatar asked Mar 12 '23 19:03

BlackAlpha


2 Answers

Ok everyone, thanks for your help. I just have to .dispose() two readers in an other function before insert/update, and it works !

like image 183
BlackAlpha Avatar answered Mar 19 '23 18:03

BlackAlpha


You're trying to run a second command before you've disposed the first. cmdExist will likely have the database locked when you try to run cmdUdpdate.

You should refactor your code so that the using blocks for your commands aren't nested.

Does SQLite lock the database file on reads? seems to suggest you'd be able to read then write, so I'd also make sure you don't have the database open from elsewhere. It does still seem to be the likely culprit though.

like image 45
Tone Avatar answered Mar 19 '23 18:03

Tone