GO初次使用连接mysql操作
- 导包go原生sdk的包还有 "github.com/go-sql-driver/mysql"
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
- 构建常量
const (
dbhost = "xx.xx.xx.xx:3306"
dbusername = "root"
dbpassword = "123"
dbname = "test"
)
- 获取数据库连接对象
func getDB() *sql.DB {
var str = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", dbusername, dbpassword, dbhost, dbname)
println(str)
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", dbusername, dbpassword, dbhost, dbname))
if err != nil {
return nil
}
return db
}
- 查询sql
func getAll() {
var db = getDB()
if db == nil {
fmt.Printf("获取连接失败", db)
return
}
rows, err := db.Query("select errorinfo, message, lastSync from error_data_record ")
if err != nil {
fmt.Println("get all error: ", err.Error())
return
}
for rows.Next() {
var errorinfo, message, lastSync string
if err := rows.Scan(&errorinfo, &message, &lastSync); err == nil {
fmt.Println("username: ", errorinfo, "departname: ", message, "created: ", lastSync)
}
}
}
- main方法调用
func main() {
getAll()
}
使用注意
github.com/go-sql-driver/mysql 包go自身是不带的 , 需要我们自己下载
步骤:
//开启go modules功能
1. go env -w GO111MODULE=on
// 在该项目目录下,初始化Go moudle
2. go mod init 文件夹名
//终端输入
3. go get github.com/go-sql-driver/mysql
报错:
go get: module github.com/go-sql-driver/mysql: Get "https://proxy.golang.org/github.com/go-sql-driver/mysql/@v/list": dial tcp 142.251.42.241:443: connect
ex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because conn
ected host has failed to respond.
//开启代理
4.go env -w GOPROXY=https://goproxy.cn,direct
//重新执行3步骤
5.再次导入包