1.导入Go-MySQL-Driver驱动包
在命令行输入
go get github.com/go-sql-driver/mysql
2.go语言连接并操作MySQL数据库
代码如下
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main(){
db,err:=sql.Open("mysql","root:123456@tcp(127.0.0.1:3306)/testgo?charset=utf8")
if err!=nil{
panic(err)
}else{
fmt.Println(db.Stats())
}
//插入用户
//statement,err:=db.Prepare("insert into user set username=?,password=?")
statement,err:=db.Prepare("insert into user(username,password) values(?,?)")
if err!=nil{
panic(err)
}else{
//fmt.Println(statement)
res,err:=statement.Exec("wangwu","wangwu1111")
if err!=nil{
panic(err)
}else{
//打印最后插入的id
fmt.Println(res.LastInsertId())
}
}
//修改用户
statement1,err:=db.Prepare("update user set username=? where id=?")
if err!=nil{
panic(err)
}else{
res,err:=statement1.Exec("wangwu1",3)
if err!=nil{
panic(err)
}else{
//打印影响的行
fmt.Println(res.RowsAffected())
}
}
//删除用户
statement2,err:=db.Prepare("delete from user where id=?")
if err!=nil{
panic(err)
}else{
res,err:=statement2.Exec(1)
if err!=nil{
panic(err)
}else{
//打印影响的行
fmt.Println(res.RowsAffected())
}
}
//rows,err:=db.Query("select * from user where id=2")
rows,err:=db.Query("select * from user where username='"+"Sarah"+"'")
for rows.Next(){
var id int
var username string
var password string
//获取一行的数据
err=rows.Scan(&id,&username,&password)
if err!=nil{
panic(err)
}else{
fmt.Println("id:",id," username:",username," password:",password)
}
}
db.Close()
}