Go Mysql使用
Go Mysql
@(Golang)
1. 安装
go get github.com/go-sql-driver/mysql
go get github.com/jmoiron/sqlx
2. 连接
database, err := sqlx.Open("mysql", "root:XXXX@tcp(127.0.0.1:3306)/test")
//database, err := sqlx.Open("数据库类型", "用户名:密码@tcp(地址:端口)/数据库名")
3. 查询
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
//create table person (user_id int not null primary key auto_increment,username varchar(100) not null default '');
type Person struct {
UserId int `db:"user_id"`
Username string `db:"username"`
}
func main() {
db, err := sqlx.Open("mysql", "root:password1@tcp(127.0.0.1:3307)/kutest")
if err != nil {
fmt.Println("open mysql fail", err)
db.Close()
return
}
var person []Person
err1 := db.Select(&person, "select user_id,username from person where user_id=?", 2)
if err1 != nil {
fmt.Println("execute fail", err1)
return
}
fmt.Println("select succ", person)
}
3. 执行语句
r, err1 := db.Exec("insert into person set user_id=?, username=? ", 10, "kevinlu")
执行后立刻commit
4. 事务
conn, err := db.Begin()
conn.Exec("insert into person set user_id=?, username=? ", 20, "kevinlu20")
conn.Exec("insert into person set user_id=?, username=? ", 21, "kevinlu21")
conn.Commit()
//conn.Rollback() //回滚