更新时间:2026-10-21 GMT+08:00
执行SQL语句
type DB的Exec类方法用于执行不返回结果集的SQL语句,比如CREATE TABLE、INSERT、UPDATE、DELETE等DDL和DML语句。
Query类方法用于执行SELECT查询语句,QueryRow(query string)只返回一个数据行,Query(query string)返回多个数据行。本节通过示例步骤呈现建表、插入、更新、删除、查询操作。
建表与插入数据
前置条件:已连接数据库,连接对象为db。
使用Exec方法执行建表与插入数据语句的步骤如下:
- 定义了清理、建表及插入数据的SQL语句切片。
sqls := []string{ "DROP TABLE IF EXISTS testExec", //若testExec表存在则删除。 "CREATE TABLE testExec(f1 int, f2 varchar(20), f3 number, f4 timestamptz, f5 boolean)", //创建testExec表。 "INSERT INTO testExec VALUES(1, 'abcdefg', 123.3, '2022-02-08 10:30:43.31 +08', true)", //插入一条数据。 "INSERT INTO testExec VALUES(:f1, :f2, :f3, :f4, :f5)", //参数化插入语句。 } - 定义数据切片。
intF1 := []int{2, 3, 4, 5, 6} intF2 := []string{"hello world", "服务端", "客户端", "CPU", "GPU"} intF3 := []float64{641.43, 431.54, 5423.52, 665537.63, 6503.1} intF4 := []time.Time{ time.Date(2022, 2, 8, 10, 35, 43, 623431, time.Local), time.Date(2022, 2, 10, 19, 11, 54, 353431, time.Local), time.Date(2022, 2, 12, 6, 11, 15, 636431, time.Local), time.Date(2022, 2, 14, 4, 51, 22, 747653, time.Local), time.Date(2022, 2, 16, 13, 45, 55, 674636, time.Local), } intF5 := []bool{false, true, false, true, true} - 通过循环结构和range关键字遍历sqls切片,调用Exec方法执行一系列SQL语句(包括清理、建表和插入操作)。
for _, s := range sqls { if strings.Contains(s, ":f") { //判断是否参数化SQL。 for i, _ := range intF1 { //遍历数据索引。 _, err := db.Exec(s, intF1[i], intF2[i], intF3[i], intF4[i], intF5[i]) //执行参数化插入。 if err != nil { log.Fatal(err) } } } else { // 非参数化SQL。 _, err = db.Exec(s) //直接执行DDL。 if err != nil { log.Fatal(err) } } }
更新数据
前置条件:已执行建表与插入数据。
使用Exec方法执行更新数据语句的步骤如下:
- 非参数化更新:将f1=1的记录的f2字段更新为'updated_value'。
_, err = db.Exec("UPDATE testExec SET f2 = 'updated_value' WHERE f1 = 1") if err != nil { log.Fatal(err) } - 参数化更新:根据f1的值更新对应记录的f2、f3、f5字段。
updateF1 := []int{2, 3} updateF2 := []string{"updated_hello", "updated_server"} updateF3 := []float64{999.99, 888.88} updateF5 := []bool{true, false} for i, _ := range updateF1 { _, err := db.Exec("UPDATE testExec SET f2 = :f2, f3 = :f3, f5 = :f5 WHERE f1 = :f1", updateF2[i], updateF3[i], updateF5[i], updateF1[i]) if err != nil { log.Fatal(err) } }
- 非参数化删除:删除f1=6的记录。
_, err = db.Exec("DELETE FROM testExec WHERE f1 = 6") if err != nil { log.Fatal(err) } - 参数化删除:根据f1的值删除对应记录。
deleteF1 := []int{4, 5} for i, _ := range deleteF1 { _, err := db.Exec("DELETE FROM testExec WHERE f1 = :f1", deleteF1[i]) if err != nil { log.Fatal(err) } }
父主题: 开发步骤