Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database is locked (defering rows didn't work)

Tags:

sqlite

go

I have a problem with SQLite3 in my Golang project. I want to insert data into my database but It gives me error database is locked. I know that it was here the same question (Sqlite3 error: database is locked in golang) but answer from there didn't work. I don't know what I'm doing wrong. Here is my code:

var (
    tpl   *template.Template
    db, _ = sql.Open("sqlite3", "database/pastozbior.db")
)
func main() {
    http.HandleFunc("/", addCopypasta)
    http.ListenAndServe(":8000", nil)
} 
func getCopypasta() []Copypasta {
    copypastaList := []Copypasta{}
    var title, body string

    rows, _ := db.Query("select title, body from copypasta")
    for rows.Next() {
        rows.Scan(&title, &body)
        copypastaList = append(copypastaList, Copypasta{title, body})
    }
    defer rows.Close()
    return copypastaList
}

func addCopypasta(w http.ResponseWriter, r *http.Request) {
    tpl.ExecuteTemplate(w, "main.html", nil)

    if r.Method == "POST" {
        r.ParseForm()
        // add copypasta to database
        stmt, err := db.Prepare("INSERT INTO copypasta(title, body, approved) values(?,?,0)")
        if err != nil {
            log.Fatal(err)
        }

        res, err := stmt.Exec("testTitle", "TestBody")
        if err != nil {
            log.Fatal(err)
        }
        id, err := res.LastInsertId()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(id)

    }
}

Thanks in advance for the help!

like image 972
xaos_xv Avatar asked Jun 18 '18 11:06

xaos_xv


1 Answers

You must place defer rows.Close() directly below the row where your Rows are created. Because, in your case when there is a panic while doing something, the defer is never reached and the rows are never closed, and then such an error situation can occur. In your code, you throw away the great advantage the defer-construct in go has above other programming environments.

like image 175
Bert Verhees Avatar answered Oct 01 '22 19:10

Bert Verhees