Home > Software design >  Received Sqlite error database is locked in iOS when reading data
Received Sqlite error database is locked in iOS when reading data

Time:10-02

I was getting the error "database is locked" after executing the following query

func readIdComposicagoPelagem(_ idEspecie:Int, _ idPelagem:Int, _ idStPelagem:Int) -> Int {
    let idComp = 0
    
    let queryStatementString = "SELECT idComp FROM RES_COMP_PELAGEM where idEspecie = \(idEspecie) and idPelagem = \(idPelagem) and idStPelagem = \(idStPelagem);"
    var queryStatement: OpaquePointer? = nil
    
    if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement, nil) == SQLITE_OK {
        while sqlite3_step(queryStatement) == SQLITE_ROW {
            let ident = sqlite3_column_int(queryStatement, 0)
            debugPrint("Query Result RES_COMP_PELAGEM:")
            debugPrint("ident: \(ident) ")
    
            return Int(ident)
        }
    } else {
        debugPrint("SELECT statement could not be prepared - RES_COMP_PELAGEM")
    }
    sqlite3_finalize(queryStatement)        
    
    return idComp
}

After run the function above, all other queries that modify data (delete, update, insert) does not work anymore. But select statements continue to work.

How can I fix that?

I never use sqlite3_close() and it was working properly some time ago. but now I don't know why the function above is locking the database.

Any idea of how to fix that?

CodePudding user response:

Based in the comment of @TonyMkenu

I change the code to fix the problem.

func readIdComposicagoPelagem(_ idEspecie:Int, _ idPelagem:Int, _ idStPelagem:Int) -> Int {
    var idComp = 0
    
    let queryStatementString = "SELECT idComp FROM RES_COMP_PELAGEM where idEspecie = \(idEspecie) and idPelagem = \(idPelagem) and idStPelagem = \(idStPelagem);"
    var queryStatement2: OpaquePointer? = nil
    
    if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement2, nil) == SQLITE_OK {
        while sqlite3_step(queryStatement2) == SQLITE_ROW {
            let ident = sqlite3_column_int(queryStatement2, 0)
            debugPrint("Query Result RES_COMP_PELAGEM:")
            debugPrint("ident: \(ident) ")
    
            idComp = Int(ident)
            
        }
    } else {
        debugPrint("SELECT statement could not be prepared - RES_COMP_PELAGEM")
    }
    sqlite3_finalize(queryStatement2)
    
    return idComp
}
  • Related