5

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!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
xaos_xv
  • 759
  • 1
  • 10
  • 27
  • 1
    I think you should move the _defer_ stuff just under the query call, and handle the transaction too. The difference with the other question is that you have an _insert_ command, and you don't take care of the transaction there. – Mario Santini Jun 18 '18 at 11:50
  • can you query through cli ? – CallMeLoki Jun 18 '18 at 12:17

1 Answers1

6

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.

Bert Verhees
  • 1,057
  • 3
  • 14
  • 25