golang连接mysql
- mysql数据驱动:github.com/go-sql-driver/mysql
安装:
go get -u github.com/go-sql-driver/mysql
- 构建连接, 格式是:”用户名:密码@tcp(IP:端口)/数据库?charset=utf8”
- 打开数据库,前者是驱动名,所以要导入:_ “github.com/go-sql-driver/mysql”
初始化
func init(){
db,err:=sql.Open("mysql","root:1111@tcp(127.0.0.1:3306)/test?charset=utf8")
if err!=nil{
fmt.Println("dbiniterr:",err)
}
}
插入数据 insert
插入前需要提前登录mysql创建表对应的字段。
typeDBworkerstruct{
Db*sql.DB
}
//插入数据测试
func(dbw*DBWorker)insertData(){
//stmt,_:=dbw.Db.Prepare(`INSERTINTOuser1(name,age)VALUES(?,?)`)
//deferstmt.Close()
stmt,err:=dbw.Db.Prepare("INSERTINTO user1 (`user`,`age`) VALUES (?,?)")
if err!=nil{
fmt.Println("Preparefail",err)
return
}
ret,err:=stmt.Exec(1,23)
if err!=nil{
fmt.Printf("insertdataerror:%v\n",err)
return
}
if LastInsertId,err:=ret.LastInsertId();err==nil{
fmt.Printf("LastInsertId%d\n",LastInsertId)
}
if RowsAffected,err:=ret.RowsAffected();err==nil{
fmt.Printf("RowsAffected%d\n",RowsAffected)
}
}
查询数据测试
func (dbw *DBWorker) queryData() {
stmt, _ := dbw.Db.Prepare("SELECT * FROM user WHERE age = ?")
defer stmt.Close()
user := userTB{}
//查询user表中age等于23的数据
rows, err := stmt.Query(23)
defer rows.Close()
if err != nil {
fmt.Printf("query data error : %v\n", err)
return;
}
有疑问加站长微信联系(非本文作者)