更新时间:2026-07-28 GMT+08:00
执行SQL语句
type DB的Exec类方法用于执行不返回结果集的SQL语句,比如CREATE TABLE、INSERT、UPDATE、DELETE等DDL和DML语句。Query类方法用于执行SELECT查询语句。
Exec类方法
以下给出Exec方法使用的一个示例(完整示例请参考示例一)。
前提条件:已经连接数据库,连接对象为db。
- 定义包含4个SQL语句的字符串切片。
sqls := []string{ "DROP TABLE IF EXISTS testExec", "CREATE TABLE testExec(f1 int, f2 varchar(20), f3 number, f4 timestamptz, f5 boolean)", "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", "华为", "北京", "nanjing", "研究所"} 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) } } }
Query类方法
调用Exec方法向testExec表插入数据后,可以调用Query类方法执行返回结果集的SQL语句,QueryRow(query string)只返回一个数据行,Query(query string)返回多个数据行。
以下给出Query类方法使用的示例(完整示例请参考示例一)。
父主题: 开发步骤