sqlite database is locked on insertion

て烟熏妆下的殇ゞ 提交于 2019-12-20 02:04:53

问题


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.


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/22612790/sqlite-database-is-locked-on-insertion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!