在我的小型Web服务中,尝试在日志表中插入新行时出现死锁 - 错误1213:尝试锁定时发现死锁;尝试重新启动事务。
当我多次执行方法测试时,我收到错误。我怎样才能避免死锁?
func main() {
var err error
db, err = sql.Open("mysql", dbUser+":"+dbPassword+"@tcp("+dbAddr+")/"+dbDatabase)
if err != nil {
panic(err.Error())
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err.Error())
}
defer db.Close()
router := mux.NewRouter()
router.HandleFunc("/test/", Test).Methods("POST")
log.Error(http.ListenAndServe(":8080", router))
}
func Test(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(body)
_ = insertLog("Test")
}
func insertLog(msg string) error {
var sqlString string
sqlString = "insert into logs (date_time, msg) values(now(),?)"
stmt, err := db.Prepare(sqlString)
if err != nil {
log.Error(err)
return err
}
defer stmt.Close()
_, err = stmt.Exec(msg)
if err != nil {
log.Error("Msg: %s, Func: %s", err, function)
return err
}
defer stmt.Close()
return err
}
架构(来自评论):
CREATE TABLE IF NOT EXISTS logs (
date_time datetime NOT NULL,
msg varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
答案 0 :(得分:-2)
你没有PRIMARY KEY
;那很顽皮。
添加
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
到表定义。 (见ALTER TABLE
。)