go原生mysql链接
var DB *sql.DB
func InitDB(){ path := strings.Join([]string{USERNAME, ":", PASSWORD, "@tcp(",HOST, ":", PORT, ")/", DBNAME, "?charset=utf8"}, "") DB, _ = sql.Open("mysql", path) DB.SetConnMaxLifetime(10) DB.SetMaxIdleConns(5) if err := DB.Ping(); err != nil{ fmt.Println("opon database fail") return } fmt.Println("connnect success") }
func InsertSql(movieData MovieData) bool {
tx, err := DB.Begin()
if err != nil {
fmt.Println("tx fail")
return false
}
stmt, err := tx.Prepare("INSERT INTO movie_data (`Title`,`Director`,`Picture`,`Actor`,`Year`,`Score`,`Quote`) VALUES (?, ?, ?,?,?,?,?)")
if err != nil {
fmt.Println("Prepare fail", err)
return false
}
_, err = stmt.Exec(movieData.Title, movieData.Director, movieData.Picture, movieData.Actor, movieData.Year, movieData.Score, movieData.Quote)
if err != nil {
fmt.Println("Exec fail", err)
return false
}
_ = tx.Commit()
return true
}