Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite3 error: database is locked in golang

Tags:

sqlite

go

I'm using sqlite3 database in golang and I got the error: "database is locked."

I know there can't be multiple threads using same database file.

Although I get only one connection in my program I close all query results, but it always creates 2 or 3 handles of the database file.

I could check this out by using the Opendfileview program.

The following code creates two database file handles.

func main() {
    database, tx, err := getDatabaseHandle()
    if err != nil {
        log.Fatal(err)
    }
    defer database.Close()
    dosomething(database, tx)
}
func dosomething(database *sql.DB, tx *sql.Tx) error {
    rows, err := database.Query("select * from sometable where name=?","some")
    if err != nil {
        return err
    }
    if rows.Next() {
        ...
    }
    rows.Close()
    //some insert queries
    tx.Commit()
}
func getDatabaseHandle() (*sql.DB, *sql.Tx, error) {
    database, err := sql.Open("sqlite3", dbPath)
    if err != nil {
        fmt.Println("Failed to create the handle")
        return nil, nil, err
    }
    if err2 := database.Ping(); err2 != nil {
        fmt.Println("Failed to keep connection alive")
        return nil, nil, err
    }
    tx, err := database.Begin()
    if err != nil {
        return nil, nil, err
    }
    return database, tx, nil
}
like image 477
superuser123 Avatar asked Sep 09 '15 12:09

superuser123


1 Answers

Try defering the rows.Close():

if err != nil {
    return err
}
defer rows.Close()
if rows.Next() {
    ...
}
like image 136
Pablo Fernandez Avatar answered Sep 20 '22 02:09

Pablo Fernandez