duanjinchen5296
duanjinchen5296
2015-09-09 12:02

SQLite3错误:数据库被锁定在Golang中

已采纳

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 and close all results of queries, but it always creates 2 or 3 handles of the database file.

I cloud check about it by using opendfileview program.

Can anybody help me with this problem. Thanks in advance.

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
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doujia1904 doujia1904 6年前

    Try defering the rows.Close():

    if err != nil {
        return err
    }
    defer rows.Close()
    if rows.Next() {
        ...
    }
    
    点赞 评论 复制链接分享

相关推荐