安装驱动
go get -u -v github.com/go-sql-driver/mysql
代码:
注:import "github.com/go-sql-driver/mysql",并且在其前面加上“_”.这是因为mysql驱动需要初始化,因此需要引入包,但在这个文件中,这个包并没有被直接使用,所有前面加上“_”
package models
import (
"database/sql"
"fmt"
"github.com/astaxie/beego"
_ "github.com/go-sql-driver/mysql"
)
func init() {
//操作数据库代码
//第一个参数是数据库驱动
//第二个参数是链接数据库字符串
//u:u@tcp(127.0.0.1:3306)
conn, err := sql.Open("mysql", "u:u@tcp(127.0.0.1:3306)/u?charset=utf8")
if err != nil {
beego.Error("链接错误", err)
return
}
/*
//创建表
_, err = conn.Exec("create table user(name varchar(40) ,password varchar(40) )")
if err != nil {
beego.Error("创建表失败", err)
}
*/
/*
//插入数据
conn.Exec("insert into user values(?,?)","tom","000000")
*/
/*
//插入多条数据(预处理)
users:=[][]string{{"lilei","000000"},{"hanmeimei","000000"}}
stat,_:=conn.Prepare("insert into user values(?,?)")
for _,s:=range users{
stat.Exec(s[0],s[1])
}
*/
//查询多行数据
res, err := conn.Query("select * from user ")
fmt.Println(res)
var person user
for res.Next() {
res.Scan(&person.name, &person.password)
beego.Info(person)
}
//关闭数据库连接
conn.Close()
}
type user struct {
name string
password string
}
网友评论