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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With