本文结合使用场景简单介绍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

Go sql insert update使用举例的更多相关文章

  1. Linq to SQL -- Insert、Update、Delete

    Insert/Update/Delete操作 插入(Insert) 1.简单形式 说明:new一个对象,使用InsertOnSubmit方法将其加入到对应的集合中,使用SubmitChanges()提 ...

  2. sql中同一个Trigger里同时包含Insert,Update,Delete

    sql中同一个Trigger里同时包含Insert,Update,Delete SQLServer是靠Inserted表和Deleted表来处理的,判断一下就可以了,只不过比ORACLE麻烦一点 cr ...

  3. sql insert、update、delete完以后返回主键ID

    以前只用过在insert完以后利用select @@IDENTITY返回主键ID,最近在做微信公众平台,遇到一个需求是在帮绑定万微信openid后自动完成登陆,这就需要update以后返回主键ID,查 ...

  4. LINQ体验(9)——LINQ to SQL语句之Insert/Update/Delete操作

    我们继续讲解LINQ to SQL语句,这篇我们来讨论Insert/Update/Delete操作.这个在我们的程序中最为常用了.我们直接看例子. Insert/Update/Delete操作 插入( ...

  5. 踩坑事件:不能对基于文本的临时表使用sql insert语句

    先来描述一下问题: 如果你是从基于文本的数据源来创建DataFrame的,当你将DataFrame注册为临时表后,如果对这个临时表进行insert into 操作,会抛出异常的. 问题答案参见:htt ...

  6. 关于MyBatis mapper的insert, update, delete返回值

    这里做了比较清晰的解释: http://mybatis.github.io/mybatis-3/java-api.html SqlSession As mentioned above, the Sql ...

  7. PHP5: mysqli 插入, 查询, 更新和删除 Insert Update Delete Using mysqli (CRUD)

    原文: PHP5: mysqli 插入, 查询, 更新和删除  Insert Update Delete Using mysqli (CRUD) PHP 5 及以上版本建议使用以下方式连接 MySQL ...

  8. 《oracle每天一练》Merge Into 语句代替Insert/Update在Oracle中的应用实战

    转载自窃破天道 动机: 想在Oracle中用一条SQL语句直接进行Insert/Update的操作. 说明: 在进行SQL语句编写时,我们经常会遇到大量的同时进行Insert/Update的语句 ,也 ...

  9. 使用Merge Into 语句实现 Insert/Update

    网址: http://www.eygle.com/digest/2009/01/merge_into_insertupdate.html 动机: 想在Oracle中用一条SQL语句直接进行Insert ...

随机推荐

  1. 常见无线DOS攻击

    记录下自己最近一段时间对无线渗透学习的笔记. 无线DOS就是无线拒绝服务攻击.主要包括以下几种攻击类型:Auth Dos攻击.Deauth Flood攻击.Disassociate攻击及RF干扰攻击等 ...

  2. python点滴:判断字符串是否为合法json格式

    在一些情况下,我们需要判断字符串是否为合法json格式. 思路很简单:尝试对字符串使用json.loads(),如果不是合法json格式,则会抛出ValueError异常. 示例如下: import ...

  3. HDU 6095 17多校5 Rikka with Competition(思维简单题)

    Problem Description As we know, Rikka is poor at math. Yuta is worrying about this situation, so he ...

  4. vue mapbox 地图 demo

    执行以下命令: npm install --save mapbox-gl// cnpm install --save mapbox-gl <template> <div style= ...

  5. PAP认证(单向、双向)

    实验要求:掌握PAP单向.双向认证 拓扑如下: 单向验证 R1(认证方)enable 进入特权模式configure terminal 进入全局模式hostname R1 设置主机名interface ...

  6. Coach Said No Worry

    I have been losing memories those days. I can't get through what I was doing right then. I have prom ...

  7. Maxscale-在第一个节点的配置

    [maxscale]threads=4 ##### Write Service, need to set address[server1]type=serveraddress=172.16.50.36 ...

  8. Gym - 101806T: Touch The Sky(贪心)

    Figure: The house floats up in the sky by balloons. This picture is also used in 2018 KAIST RUN Spri ...

  9. day02编程语言介绍及python介绍

    编程语言介绍 机器语言:以二进制数为代码的编程语言,直接控制硬件运行 优点:执行效率非常快 缺点:以二进制数为编码编程,编程效率非常低下,掌握它需要深厚的硬件原理功底 汇编语言:将二进制编码用英文字符 ...

  10. FTP相关、用vsftpd搭建ftp、xshell使用xftp传输文件、使用pure-ftpd搭建ftp服务

    1.FTP相关(file transfer protocol,文件传输协议)   2.用vsftpd搭建ftp安装:yum install vsftpd -y创建一个虚拟用户:useradd  vft ...