This article combines the use of a scenario with a simple introduction to the use of INSERT, update in SQL.
Here's the code:
If the record already exists, it is updated, otherwise a new record is inserted.
Package Mainimport ("Database/sql" "FMT" "Log" "Time" _ "Github.com/go-sql-driver/mysql") var DB *sql. Dbvar dataBase = "root:[email protected" (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 (DB). Setmaxidleconns () Err = DB. Ping () if err! = Nil {log. Fatalln ("Ping db Fail:", err)}}func main () {Init () entry ()}//update First, if not exist, then try to Insertfun C 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
The first execution, the record does not exist, the update does not affect any rows, and then an insert operation is attempted.
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
Execute again, there is already a record of the same IP, and only the update is performed:
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
Go SQL Insert Update Use example