Go sql insert update使用举例

时间:2021-02-20 04:27:40

本文结合使用场景简单介绍sql中的insert、update的使用。

以下是代码:

如果记录已经存在,则更新,否则插入新记录。

package main

import (
"database/sql"
"fmt"
"log"
"time" _ "github.com/go-sql-driver/mysql" ) var DB *sql.DB var dataBase = "root:123456@tcp(127.0.0.1:3306)/web_portal?loc=Local&parseTime=true" func Init() {
var err error
DB, err = sql.Open("mysql", dataBase)
if err != nil {
log.Fatalln("open db fail:", err)
} DB.SetMaxOpenConns(20)
DB.SetMaxIdleConns(15) err = DB.Ping()
if err != nil {
log.Fatalln("ping db fail:", err)
}
} func main() { Init() entry() } // update first, if not exist, then try to insert
func entry() { now := time.Now().Unix()
sql := fmt.Sprintf(
"update tbl_host set version='%s', timestamp='%d' where ip='%s'",
"3.20.2",
now,
"192.168.11.23",
) log.Println("sql:", sql) result, err := DB.Exec(sql)
if err != nil {
log.Println("exec failed:", err, ", sql:", sql)
return
} idAff, err := result.RowsAffected()
if err != nil {
log.Println("RowsAffected failed:", err)
return
}
log.Println("id:", idAff)
if idAff == 0 {
sql := fmt.Sprintf(
"insert into tbl_host(ip, version, timestamp) values ('%s', '%s', '%d')",
"192.168.11.23",
"3.20.1",
now,
) log.Println("not exsit, then try to insert")
tryInsert(sql) } log.Println("sucess")
} func tryInsert(sql string) { _, err := DB.Exec(sql)
if err != nil {
log.Println("exec failed:", err, ", sql:", sql)
} }

output:

第一次执行,记录不存在,update不影响任何行,然后尝试insert操作。

2018/04/30 22:15:13 sql: update tbl_host set version='3.20.2', timestamp='1525097713' where ip='192.168.11.23'

2018/04/30 22:15:13 id: 0

2018/04/30 22:15:13 not exsit, then try to insert

2018/04/30 22:15:13 sucess

再次执行,此时已经存在同一个ip的记录,只会执行update更新:

2018/04/30 22:13:30 sql: update tbl_host set version='3.20.2', timestamp='1525097610' where ip='192.168.11.22'

2018/04/30 22:13:30 id: 1

2018/04/30 22:13:30 sucess