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
}
Try defering the rows.Close()
:
if err != nil {
return err
}
defer rows.Close()
if rows.Next() {
...
}