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!
答案 0 :(得分:4)
您必须将row.Close()直接放在创建行的行的下方。 因为,在你做某事时出现恐慌的情况下,永远不会达到延迟,并且行永远不会关闭,然后就会出现这样的错误情况。在你的代码中,你抛弃了defer-construct in go高于其他编程环境的巨大优势。