安装MySQL数据库
MySQL官方链接:https://dev.mysql.com/downloads/mysql/
Debian:sudo apt install mysql-5.7
安装过程:略
Go 安装MySQL驱动
go get "github.com/go-sql-driver/mysql"
在项目中使用MySQL
在go mod模式下,还需要在项目中引用mysql模块
go.mod文件
module MonaGinWeb
go 1.15
require (
github.com/gin-gonic/gin v1.6.3
github.com/go-sql-driver/mysql v1.5.0
)
在go中连接MySQL
import (
"database/sql"
"log"
"strconv"
)
var db *sql.DB
func init() {
c := MySQLConnInfo{
user: "",
password: "",
connMethod: "tcp",
host: "",
port: 0,
dbname: "",
otherArgs: "",
}
//数据库连接字符串
//"user:password@tcp(host:port)/dbname"
connStr := c.user + ":" + c.password +
"@" + c.connMethod + "(" + c.host + ":" + strconv.Itoa(c.port) + ")/" +
c.dbname + c.otherArgs
if temp, err := sql.Open("mysql", connStr); err == nil {
db = temp
} else { //连接出现错误
log.Fatal(err.Error())
return
}
}
func Open(driverName string, dataSourceName string) (*DB, error)
:该函数用于打开程序与SQL数据库的连接。其会返回创建(连接成功)的一个DB指针,有两个参数:driverName string
:用于指定数据库引擎dataSourceName string
:用于传入数据库的连接字符串
MySQL的增删改查
(待补充)