首先引入我们需要的第三方库
go get github.com/go-sql-driver/mysql
go get github.com/jmoiron/sqlx
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
链接mysql数据库
func init(){
database, err := sqlx.Open("mysql", "root:javadev@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("open mysql failed,", err)
return
}
Db = database
fmt.Println("init ....");
}
基本操作
insert
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Person struct {
UserId int `db:"user_id"`
Username string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
}
type Place struct {
Country string `db:"country"`
City string `db:"city"`
TelCode int `db:"telcode"`
}
var Db *sqlx.DB
func init() {
database, err := sqlx.Open("mysql", "root:@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("open mysql failed,", err)
return
}
Db = database
}
func main() {
r, err := Db.Exec("insert into person(username, sex, email)values(?, ?, ?)", "stu001", "man", "stu01@qq.com")
if err != nil {
fmt.Println("exec failed, ", err)
return
}
id, err := r.LastInsertId()
if err != nil {
fmt.Println("exec failed, ", err)
return
}
fmt.Println("insert succ:", id)
}
select操作
var person []Person
err := Db.Select(&person, "select user_id, username, sex, email from person where user_id=?", 1)
if err != nil {
fmt.Println("exec failed, ", err)
return
}
fmt.Println("select succ:", person)
update 操作
_, err := Db.Exec("update person set username=? where user_id=?", "stu0001", 1)
if err != nil {
fmt.Println("exec failed, ", err)
return
}
delete 操作
_, err := Db.Exec("delete from person where user_id=?", 1)
if err != nil {
fmt.Println("exec failed, ", err)
return
}
在go语言中,使用的mysql默认已经带有数据库连接池,用起来非常方便简单。