Go语言入门心法(一): 基础语法
Go语言入门心法(二): 结构体
Go语言入门心法(三): 接口
Go语言入门心法(四): 异常体系
Go语言入门心法(五): 函数
Go语言入门心法(六): HTTP面向客户端|服务端编程
Go语言入门心法(七): 并发与通道
Go语言入门心法(八): mysql驱动安装报错onnection failed
Go语言入门心法(九): 引入三方依赖
Go语言入门心法(十):Go语言操作MYSQL(CRUD)|事务处理
Go语言入门心法(十一): 文件处理
一: go连接mysql数据库
package mainimport ("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 mainimport ("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 mainimport ("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 mainimport ("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 int64deptno int64dname stringlocation 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 mainimport ("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 mainimport ("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完整文档
八: go语言预处理批量插入
预处理认知升维:
(1)sql包还提供了一种预编译的方式在执行SQL语句,通常在处理批量语句时会用到这种方式,这种方式比手动拼接字符串SQL语句高效,而且可以防止SQL注入攻击
(2) 使用Exec函数执行插入语句时,其中"?"表示参数占位符,使用这种方式参数可以有效防止出现SQL注入这类漏洞;
package main/*
(1)sql包还提供了一种预编译的方式在执行SQL语句,通常在处理批量语句时会用到这种方式,这种方式比手动拼接字符串SQL语句高效,而且可以防止SQL注入攻击
(2) 使用Exec函数执行插入语句时,其中"?"表示参数占位符,使用这种方式参数可以有效防止出现SQL注入这类漏洞;
*/
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")batchPrepareInsertCheckErr(err)// 延迟执行Closer()函数defer db.Close()// 验证连接的可用性err = db.Ping()batchPrepareInsertCheckErr(err)batchInsertSql, params := initParamData()log.Println("数据库连接成功! ")stmt, err := db.Prepare(batchInsertSql) // 预处理SQLdefer stmt.Close()batchPrepareInsertCheckErr(err)res,err := stmt.Exec(params...)batchPrepareInsertCheckErr(err)id, _ := res.LastInsertId()rowCount,err:=res.RowsAffected()batchPrepareInsertCheckErr(err)fmt.Printf("插入了 %d 条数据",rowCount)fmt.Printf("lastId: %d insert success!", id)}// 插入多条数据
func initParamData() (string, []interface{}) {data := []map[string] interface{}{{"deptid":0,"deptno": 100000011, "dname": "CPO首席产品官", "location": "北京市朝阳区三里屯大街20003号"},{"deptid":0,"deptno": 100000044, "dname": "COO首席营销官", "location": "北京市海淀区马连洼30003路"},{"deptid":0,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市昌平区龙泽苑街道200000"},{"deptid":"0","deptno": 100000044, "dname": "CTO首席技术官", "location": "北京市海淀区马连洼30003路"},{"deptid":nil,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市房山区龙泽苑街道200000"},}batchInsertSql := "insert into `sys_go_dept` values "var values []interface{}for index, row := range data {if index == len(data)-1 {batchInsertSql += "(?,?, ?, ?)"} else {batchInsertSql += "(?,?, ?, ?), "}values = append(values,row["deptid"], row["deptno"], row["dname"], row["location"])}fmt.Println("batchInsertSql:", batchInsertSql)fmt.Println("values: ", values)return batchInsertSql, values
}func batchPrepareInsertCheckErr(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__4_.exe D:\program_file\go_workspace\org.jd.data\database\OOPMysqlToDatabasePrepareBatchInsertGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database__4_.exe
batchInsertSql: insert into `sys_go_dept` values (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?)
values: [0 100000011 CPO首席产品官 北京市朝阳区三里屯大街20003号 0 100000044 COO首席营销官 北京市海淀区马连洼30003路 0 100000055 CFO首席财务官 北京市昌平区龙泽苑街道200000 0 100000044 CTO首席技术官 北京市海淀区马连洼30003路 <nil> 100000055 CFO首席财务官 北京市房山区龙泽苑街道200000]
2023/10/19 12:24:41 数据库连接成功!插入了 5 条数据lastId: 44 insert success!
Process finished with the exit code 0
说明: batchInsertSql: insert into `sys_go_dept` values (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?)
从拼接的insert into `sys_go_dept`语句可以看得出,不用指定具体的插入字段,主键自增长, 此时,主键赋值o或者时nil,从而可以添加全部数据,而不用特意指定那几列添加数据
九: go语言操作数据看事务处理
package main/*
go语言操作数据库时事务处理(ACID)
*/
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")batchPrepareTxInsertCheckErr(err)// 延迟执行Closer()函数defer db.Close()// 验证连接的可用性err = db.Ping()batchPrepareTxInsertCheckErr(err)batchInsertSql, params := initParamDataTx()log.Println("数据库连接成功! ")tx,err :=db.Begin()batchPrepareTxInsertCheckErr(err)stmt, err := db.Prepare(batchInsertSql) // 预处理SQLcheckErrWithTx(err,tx) // 执行回滚defer stmt.Close()batchPrepareTxInsertCheckErr(err)res,err := stmt.Exec(params...)checkErrWithTx(err,tx) // 执行回滚tx.Commit() // 提交println("事务处理完毕")id, _ := res.LastInsertId()rowCount,err:=res.RowsAffected()batchPrepareTxInsertCheckErr(err)fmt.Printf("插入了 %d 条数据",rowCount)fmt.Printf("lastId: %d insert success!", id)}// 插入多条数据
func initParamDataTx() (string, []interface{}) {data := []map[string] interface{}{{"deptid":0,"deptno": 100000011, "dname": "CPO首席产品官", "location": "北京市朝阳区三里屯大街20003号"},{"deptid":0,"deptno": 100000044, "dname": "COO首席营销官", "location": "北京市海淀区马连洼30003路"},{"deptid":0,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市昌平区龙泽苑街道200000"},{"deptid":"0","deptno": 100000044, "dname": "CTO首席技术官", "location": "北京市海淀区马连洼30003路"},{"deptid":nil,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市房山区龙泽苑街道200000"},{"deptid":0,"deptno": 100000011, "dname": "CPO首席产品官", "location": "北京市朝阳区三里屯大街20003号"},{"deptid":0,"deptno": 100000044, "dname": "COO首席营销官", "location": "北京市海淀区马连洼30003路"},{"deptid":0,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市昌平区龙泽苑街道200000"},{"deptid":"0","deptno": 100000066, "dname": "CTO首席技术官", "location": "北京市海淀区马连洼30003路"},{"deptid":nil,"deptno": 100000077, "dname": "CFO首席财务官", "location": "北京市房山区龙泽苑街道200000"},{"dname": "CPO首席产品官", "location": "北京市朝阳区三里屯大街20003号"},{"deptid":0,"deptno": 100000088, "dname": "COO首席营销官", "location": "北京市海淀区马连洼30003路"},{"deptid":0,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市昌平区龙泽苑街道200000"},{"deptid":"0","deptno": 100000099, "dname": "CTO首席技术官", "location": "北京市海淀区马连洼30003路"},{"deptid":nil,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市房山区龙泽苑街道200000"},{"deptid":0,"deptno": 100000011, "dname": "CPO首席产品官", "location": "北京市朝阳区三里屯大街20003号"},{"deptid":0,"deptno": 100000044, "dname": "COO首席营销官", "location": "北京市海淀区马连洼30003路"},{"deptid":0,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市昌平区龙泽苑街道200000"},{"deptid":"0","deptno": 100000044, "dname": "CTO首席技术官", "location": "北京市海淀区马连洼30003路"},{"deptid":nil,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市房山区龙泽苑街道200000"},{"deptid":0,"deptno": 100000011, "dname": "CPO首席产品官", "location": "北京市朝阳区三里屯大街20003号"},{"deptid":0,"deptno": 100000044, "dname": "COO首席营销官", "location": "北京市海淀区马连洼30003路"},{"deptid":0,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市昌平区龙泽苑街道200000"},{"deptid":"0","deptno": 100000066, "dname": "CTO首席技术官", "location": "北京市海淀区马连洼30003路"},{"deptid":nil,"deptno": 100000077, "dname": "CFO首席财务官", "location": "北京市房山区龙泽苑街道200000"},{"deptid":0,"deptno": 100000011, "dname": "CPO首席产品官", "location": "北京市朝阳区三里屯大街20003号"},{"deptid":0,"deptno": 100000088, "dname": "COO首席营销官", "location": "北京市海淀区马连洼30003路"},{"deptid":0,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市昌平区龙泽苑街道200000"},{"deptid":"0","deptno": 100000099, "dname": "CTO首席技术官", "location": "北京市海淀区马连洼30003路"},{"deptid":nil,"deptno": 100000055, "dname": "CFO首席财务官", "location": "北京市房山区龙泽苑街道200000"},}batchInsertSql := "insert into `sys_go_dept` values "var values []interface{}for index, row := range data {if index == len(data)-1 {batchInsertSql += "(?,?, ?, ?)"} else {batchInsertSql += "(?,?, ?, ?), "}values = append(values,row["deptid"], row["deptno"], row["dname"], row["location"])}fmt.Println("batchInsertSql:", batchInsertSql)fmt.Println("values: ", values)return batchInsertSql, values
}func batchPrepareTxInsertCheckErr(err error){if err != nil {log.Fatal("系统异常: ", err.Error())}
}// 事务回滚
func checkErrWithTx(err error,tx *sql.Tx) {if err != nil {tx.Rollback()log.Fatal("系统异常,事务将回滚:",err)}
}
运行效果:
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\OOPMysqlToDatabaseTxInsertGrammar.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_database.exe
batchInsertSql: insert into `sys_go_dept` values (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?), (?,?, ?, ?)
values: [0 100000011 CPO首席产品官 北京市朝阳区三里屯大街20003号 0 100000044 COO首席营销官 北京市海淀区马连洼30003路 0 100000055 CFO首席财务官 北京市昌平区龙泽苑街道200000 0 100000044 CTO首席技术官 北京市海淀区马连洼30003路 <北京市朝阳区三里屯大街20003号 0 100000044 COO首席营销官 北京市海淀区马连洼30003路 0 100000055 CFO首席财务官 北京市昌平区龙泽苑街道200000 <nil> <nil> CTO首席技术官 北京市海淀区马连洼30003路 <nil> 100000077 CFO首席财务官 北京市房OO首席营销官 北京市海淀区马连洼30003路 0 100000055 CFO首席财务官 北京市昌平区龙泽苑街道200000 0 100000099 CTO首席技术官 北京市海淀区马连洼30003路 <nil> 100000055 CFO首席财务官 北京市房山区龙泽苑街道200000 0 100000011 CPO首席产品官 北京市朝阳区三里屯大街20003号 0 100000044 COO
首席营销官 北京市海淀区马连洼30003路 0 100000055 CFO首席财务官 北京市昌平区龙泽苑街道200000 0 100000044 CTO首席技术官 北京市海淀区马连洼30003路 <nil> 100000055 CFO首席财务官 北京市房山区龙泽苑街道200000 0 100000011 CPO首席产品55 CFO首席财务官 北京市昌平区龙泽苑街道200000 0 100000066 CTO首席技术官 北京市海淀区马连洼30003路 <nil> 100000077 CFO首席财务官 北京市房山区龙泽苑街道200000 0 100000011 CPO首席产品官 北京市朝阳区三里屯大街20003号 0 100000088 C 100000099 CTO首席技术官 北京市海淀区马连洼30003路 <nil> 100000055 CFO首席财务官 北京市房山区龙泽苑街道200000]
2023/10/20 17:23:45 数据库连接成功!
2023/10/20 17:23:45 系统异常,事务将回滚:Error 1048 (23000): Column 'deptno' cannot be null
十: 异常:converting argument $1 type: unsupported type []interface {}, a slice of interface
log.Println("数据库连接成功! ")
tx,err :=db.Begin()
batchPrepareTxInsertCheckErr(err)
stmt, err := db.Prepare(batchInsertSql) // 预处理SQL
checkErrWithTx(err,tx) // 执行回滚
defer stmt.Close()
batchPrepareTxInsertCheckErr(err)
res,err := stmt.Exec(params)
checkErrWithTx(err,tx) // 执行回滚
tx.Commit() // 提交
println("事务处理完毕")
id, _ := res.LastInsertId()
如上述代码,stmt.Exec(params) 出入参数即报错: sql: converting argument $1 type: unsupported type []interface {}, a slice of interface;
字面意思是sqlx在解析两个占位符并试图填入参数时,第一个参数类型是空指针的切片,而预期是args这个可变参数中的第一个。
因而了解了一下golang中的可变参数,即…运算符
当…Type做为参数时,本质上函数会把参数转化成一个Type类型的切片,因而在上述代码中,Service层调以可变参数形式传入一个参数,在Exec中的args就已经是[]interface{}类型了,若是直接把args做为func (s *Stmt) Exec args …interface{}) (Result, error)的参数,对于Exec来讲,收到的args就只有一个长度为1的切片,其元素类型为[]interface{},因而就有了上述的报错,解决办法很简单,就是在一个slice后加上…,这样就能把它拆包成一个可变参数的形式传入函数。
可以查看下Exce源代码:
/ Exec executes a prepared statement with the given arguments and // returns a Result summarizing the effect of the statement. // // Exec uses context.Background internally; to specify the context, use // ExecContext. func (s *Stmt) Exec(args ...any) (Result, error) {return s.ExecContext(context.Background(), args...) }入参为可变参数: 函数会把参数转化成一个Type类型的切片,正确的调用方式应该是这样:
res,err := stmt.Exec(params...)