golang操作MySQL的具体案例
代码篇的基础操作:
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Profile struct {
Id int `db:"id"`
Student string `db:"student"`
}
var Db *sqlx.DB
func init() {
database, err := sqlx.Open("mysql","root:1234567890@tcp(127.0.0.1:3306)/Demo")
if err != nil {
fmt.Println("open mysql failed,", err)
return
}
Db = database
}
func main() {
// 添加
r, err := Db.Exec("insert into profile(student)values(?)", "stu001")
if err != nil {
fmt.Println("exec failed, ", err)
return
}
id, err := r.LastInsertId()
if err != nil {
fmt.Println("exec failed, ", err)
return