Go语言入门心法(一): 基础语法
Go语言入门心法(二): 结构体
Go语言入门心法(三): 接口
Go语言入门心法(四): 异常体系
Go语言入门心法(五): 函数
Go语言入门心法(六): HTTP面向客户端|服务端编程
Go语言入门心法(八): mysql驱动安装报错onnection failed
Go语言入门心法(九): 引入三方依赖
一: go连接mysql数据库
package main
import (
"database/sql"
"fmt"
"log"
// 注册驱动器 _下划线表示执行驱动中的init函数,不使用其他函数
_ "github.com/go-sql-driver/mysql"
)
/*
go语言连接mysql数据库操作:
*/
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/tope-pay-user")
if err != nil {
fmt.Println("数据库连接异常: ", err)
}
// 延迟执行Closer()函数
defer db.Close()
// 验证连接的可用性
err = db.Ping()
if err != nil {
log.Fatal("数据库连接失败:", err)
}
log.Println("数据库连接成功: ", db.Stats())
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPMysqlToDatabaseLinkGrammar_go.exe D:\program_file\go_workspace\org.jd.data\database\OOPMysqlToDatabaseLinkGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPMysqlToDatabaseLinkGrammar_go.exe
2023/10/18 18:55:22 数据库连接成功: {0 1 0 1 0 0s 0 0 0}Process finished with the exit code 0
二: go连接mysql创建表
package main
/*
创建表:
*/
import (
"database/sql"
"fmt"
// 注册驱动器 _下划线表示执行驱动中的init函数,不使用其他函数
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/tope-pay-user")
if err != nil {
log.Fatal(err)
fmt.Println("数据库连接异常: ", err)
}
// 延迟执行Closer()函数
defer db.Close()
// 验证连接的可用性
err = db.Ping()
if err != nil {
log.Fatal("数据库连接失败:", err)
}
// 创建一张表
createTable :=
"CREATE TABLE `sys_go_dept` (" +
"`deptid` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键'," +
"`deptno` bigint(11) NOT NULL COMMENT '编码编号'," +
"`dname` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT '' COMMENT '部门名称'," +
"`location` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '地点'," +
"PRIMARY KEY (`deptid`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;"
println(createTable)
_, err = db.Exec(createTable)
if err != nil {
log.Fatal("创建表失败:", err)
}
log.Println("数据表创建成功")
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database.exe D:\program_file\go_workspace\org.jd.data\database\OOPMysqlToDatabaseCreateTableGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database.exe
CREATE TABLE `sys_go_dept` (`deptid` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键',`deptno` bigint(11) NOT NULL COMMENT '编码编号',`dname` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT '' COMMENT '部ocation` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '地点',PRIMARY KEY (`deptid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
2023/10/18 18:52:40 数据表创建成功Process finished with the exit code 0
三: go插入数据
package main
import (
"database/sql"
// 注册驱动器 _下划线表示执行驱动中的init函数,不使用其他函数
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/tope-pay-user")
checkErr(err)
// 延迟执行Closer()函数
defer db.Close()
// 验证连接的可用性
err = db.Ping()
checkErr(err)
log.Println("数据库连接成功! ")
insertSql := "insert into `sys_go_dept` (deptno,dname,location)values (?,?,?) "
rs, err := db.Exec(insertSql, 100000011, "销售总监", "北京市海淀区马连洼街道200号")
checkErr(err)
rowCount, err := rs.RowsAffected()
checkErr(err)
log.Printf("插入 %d 条数据", rowCount)
}
func checkErr(err error) {
if err != nil {
log.Fatal("系统异常: ", err.Error())
}
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__1_.exe D:\program_file\go_workspace\org.jd.data\database\OOPMysqlToDatabaseInsertGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__1_.exe
2023/10/18 19:47:03 数据库连接成功!
2023/10/18 19:47:03 插入 1 条数据Process finished with the exit code 0
四: go修改数据
package main
import (
"database/sql"
// 注册驱动器 _下划线表示执行驱动中的init函数,不使用其他函数
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/tope-pay-user")
updateCheckErr(err)
// 延迟执行Closer()函数
defer db.Close()
// 验证连接的可用性
err = db.Ping()
updateCheckErr(err)
log.Println("数据库连接成功! ")
updateSql := "update `sys_go_dept` set dname=? , location=? where deptno =? "
rs, err := db.Exec(updateSql, "CFO(首席财务官)", "北京市朝阳区三里屯大街2000号", 100000011)
updateCheckErr(err)
rowCount, err := rs.RowsAffected()
updateCheckErr(err)
if rowCount > 0 {
log.Println("更新成功")
}
}
func updateCheckErr(err error) {
if err != nil {
log.Fatal("系统异常: ", err.Error())
}
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__2_.exe D:\program_file\go_workspace\org.jd.data\database\OOPMysqlToDatabaseQueryGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__2_.exe
2023/10/18 20:31:26 数据库连接成功!
2023/10/18 20:31:27 更新成功Process finished with the exit code 0
五: go查询数据
package main
import (
"database/sql"
// 注册驱动器 _下划线表示执行驱动中的init函数,不使用其他函数
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/tope-pay-user")
queryCheckErr(err)
// 延迟执行Closer()函数
defer db.Close()
// 验证连接的可用性
err = db.Ping()
queryCheckErr(err)
log.Println("数据库连接成功! ")
querySql := "select * from sys_go_dept where deptno = ?"
rows, err := db.Query(querySql, 100000011)
// 延迟执行
defer rows.Close()
for rows.Next() {
user := User{}
// 顺序需与数据库表的字段对应
err := rows.Scan(&user.deptid, &user.deptno, &user.dname, &user.location)
queryCheckErr(err)
log.Println(user)
}
}
type User struct {
deptid int64
deptno int64
dname string
location string
}
func queryCheckErr(err error) {
if err != nil {
log.Fatal("系统异常: ", err.Error())
}
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__2_.exe D:\program_file\go_workspace\org.jd.data\database\OOPMysqlToDatabaseQueryGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__2_.exe
2023/10/18 20:54:42 数据库连接成功!
2023/10/18 20:54:42 {1 100000011 CFO(首席财务官) 北京市朝阳区三里屯大街2000号}
2023/10/18 20:54:42 {2 100000011 CFO(首席财务官) 北京市朝阳区三里屯大街2000号}
2023/10/18 20:54:42 {3 100000011 销售 北京市海淀区马连洼街道200号}Process finished with the exit code 0
六: go删除数据
package main
import (
"database/sql"
// 注册驱动器 _下划线表示执行驱动中的init函数,不使用其他函数
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/tope-pay-user")
deleteCheckErr(err)
// 延迟执行Closer()函数
defer db.Close()
// 验证连接的可用性
err = db.Ping()
deleteCheckErr(err)
log.Println("数据库连接成功! ")
deleteSql := "delete from `sys_go_dept` where deptid = ? "
rs, err := db.Exec(deleteSql, 3)
deleteCheckErr(err)
rowCount, err := rs.RowsAffected()
deleteCheckErr(err)
if rowCount > 0 {
log.Println("删除成功")
}
}
func deleteCheckErr(err error) {
if err != nil {
log.Fatal("系统异常: ", err.Error())
}
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__5_.exe D:\program_file\go_workspace\org.jd.data\database\OOPMysqlToDatabaseDeleteGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__5_.exe
2023/10/18 21:02:56 数据库连接成功!
2023/10/18 21:02:56 删除成功Process finished with the exit code 0
七: go批量插入数据
package main
import (
"database/sql"
"fmt"
"log"
// 注册驱动器 _下划线表示执行驱动中的init函数,不使用其他函数
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/tope-pay-user")
batchInsertCheckErr(err)
// 延迟执行Closer()函数
defer db.Close()
// 验证连接的可用性
err = db.Ping()
batchInsertCheckErr(err)
sqlStr, params := insertDataMap()
log.Println("数据库连接成功! ")
res, _ := db.Exec(sqlStr, params...) // params...: 解构
id, _ := res.LastInsertId()
fmt.Printf("lastId: %d insert success!", id)
}
// 插入多条数据
func insertDataMap() (string, []interface{}) {
data := []map[string]string{
{"deptno": "100000011", "dname": "CTO首席技术官", "location": "北京市朝阳区三里屯大街20003号"},
{"deptno": "100000022", "dname": "CTO首席技术官", "location": "北京市海淀区马连洼30003路"},
{"deptno": "100000033", "dname": "CEO总经理", "location": "北京市昌平区龙泽苑街道200000"},
}
batchInsertSql := "insert into `sys_go_dept` (deptno,dname,location)values "
var values []interface{}
for index, row := range data {
if index == len(data)-1 {
batchInsertSql += "(?, ?, ?)"
} else {
batchInsertSql += "(?, ?, ?), "
}
values = append(values, row["deptno"], row["dname"], row["location"])
}
fmt.Println("batchInsertSql:", batchInsertSql)
fmt.Println("values: ", values)
return batchInsertSql, values
}
func batchInsertCheckErr(err error) {
if err != nil {
log.Fatal("系统异常: ", err.Error())
}
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___2go_build_org_jd_data_org_jd_data_database__3_.exe D:\program_file\go_workspace\org.jd.data\database\OOPMysqlToDatabaseBatchInsertGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___2go_build_org_jd_data_org_jd_data_database__3_.exe
batchInsertSql: insert into `sys_go_dept` (deptno,dname,location)values (?, ?, ?), (?, ?, ?), (?, ?, ?)
values: [100000011 CTO首席技术官 北京市朝阳区三里屯大街20003号 100000022 CTO首席技术官 北京市海淀区马连洼30003路 100000033 CEO总经理 北京市昌平区龙泽苑街道200000]
2023/10/18 21:24:20 数据库连接成功!
lastId: 9 insert success!Process finished with the exit code 0
Go操作Mysql驱动实现CRUD完整文档