package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Person struct {
Id int `db:"id"`
Name string `db:"name"`
Age string `db:"age"`
}
var Db *sqlx.DB
func init() {
database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("open mysql failed,", err)
defer Db.Close() // 注意这行代码要写在上面err判断的下面
return
}
Db = database
}
func insertRecord(){
r, err := Db.Exec("insert into person(name, age)values(?, ?)", "stu001",15)
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)
}
func delRecord(){
r, err := Db.Exec("delete from person where id=?", 32)
if err != nil {
fmt.Println("exec failed, ", err)
return
}
id, err := r.RowsAffected()
if err != nil {
fmt.Println("exec failed, ", err)
return
}
fmt.Println("delete succ:", id)
}
func updateRecord(){
r, err := Db.Exec("update person set name=? where id=?", "hello", 29)
if err != nil {
fmt.Println("exec failed, ", err)
return
}
id, err := r.RowsAffected()
if err != nil {
fmt.Println("exec failed, ", err)
return
}
fmt.Println("update succ:", id)
}
func queryList(){
var person []Person
err := Db.Select(&person, "select * from person")
if err != nil {
fmt.Println("exec failed, ", err)
return
}
// id, err := r.RowsAffected()
// if err != nil {
// fmt.Println("exec failed, ", err)
// return
// }
fmt.Println("query succ:", person)
}
func main() {
//增
//insertRecord();
//删
//delRecord();
//改
//updateRecord();
//查
queryList();
}
建表
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
编码