package main

import (
"database/sql"
"fmt" _ "github.com/go-sql-driver/mysql"
) var DB *sql.DB func initDb() error {
var err error
dsn := "root:root@tcp(localhost:3306)/golang_db"
DB, err = sql.Open("mysql", dsn)
if err != nil {
return err
} DB.SetMaxOpenConns()
DB.SetMaxIdleConns()
return nil
} type User struct {
Id int64 `db:"id"`
Name sql.NullString `db:"string"`
Age int `db:"age"`
} func testQueryMultilRow() {
sqlstr := "select id, name, age from user where id > ?"
rows, err := DB.Query(sqlstr, )
//重点关注, rows对象一定要close掉
defer func() {
if rows != nil {
rows.Close()
}
}() if err != nil {
fmt.Printf("query failed, err:%v\n", err)
return
} for rows.Next() {
var user User
err := rows.Scan(&user.Id, &user.Name, &user.Age)
if err != nil {
fmt.Printf("scan failed, err:%v\n", err)
return
}
fmt.Printf("user:%#v\n", user)
} } func testQueryData() {
for i := ; i < ; i++ {
fmt.Printf("query %d times\n", i)
sqlstr := "select id, name, age from user where id=?"
row := DB.QueryRow(sqlstr, )
/*if row != nil {
continue
}*/
var user User
err := row.Scan(&user.Id, &user.Name, &user.Age)
if err != nil {
fmt.Printf("scan failed, err:%v\n", err)
return
} fmt.Printf("id:%d name:%v age:%d\n", user.Id, user.Name, user.Age)
} } func testInsertData() {
sqlstr := "insert into user(name, age) values(?, ?)"
result, err := DB.Exec(sqlstr, "tom", )
if err != nil {
fmt.Printf("insert failed, err:%v\n", err)
return
} id, err := result.LastInsertId()
if err != nil {
fmt.Printf("get last insert id failed, err:%v\n", err)
return
}
fmt.Printf("id is %d\n", id)
} func testUpdateData() {
sqlstr := "update user set name=? where id=?"
result, err := DB.Exec(sqlstr, "jim", )
if err != nil {
fmt.Printf("insert failed, err:%v\n", err)
return
} affected, err := result.RowsAffected()
if err != nil {
fmt.Printf("get affected rows failed, err:%v\n", err)
}
fmt.Printf("update db succ, affected rows:%d\n", affected)
} func testDeleteData() {
sqlstr := "delete from user where id=?"
result, err := DB.Exec(sqlstr, )
if err != nil {
fmt.Printf("insert failed, err:%v\n", err)
return
} affected, err := result.RowsAffected()
if err != nil {
fmt.Printf("get affected rows failed, err:%v\n", err)
}
fmt.Printf("delete db succ, affected rows:%d\n", affected)
} func testPrepareData() {
sqlstr := "select id, name, age from user where id > ?"
stmt, err := DB.Prepare(sqlstr)
if err != nil {
fmt.Printf("prepare failed, err:%v\n", err)
return
} defer func() {
if stmt != nil {
stmt.Close()
}
}() rows, err := stmt.Query()
//重点关注, rows对象一定要close掉
defer func() {
if rows != nil {
rows.Close()
}
}() if err != nil {
fmt.Printf("query failed, err:%v\n", err)
return
} for rows.Next() {
var user User
err := rows.Scan(&user.Id, &user.Name, &user.Age)
if err != nil {
fmt.Printf("scan failed, err:%v\n", err)
return
}
fmt.Printf("user:%#v\n", user)
}
} func testPrepareInsertData() {
sqlstr := "insert into user(name, age) values(?, ?)"
stmt, err := DB.Prepare(sqlstr)
if err != nil {
fmt.Printf("insert failed, err:%v\n", err)
return
} defer func() {
if stmt != nil {
stmt.Close()
}
}()
result, err := stmt.Exec("jim", )
id, err := result.LastInsertId()
if err != nil {
fmt.Printf("get last insert id failed, err:%v\n", err)
return
}
fmt.Printf("id is %d\n", id)
} func testTrans() { conn, err := DB.Begin()
if err != nil {
if conn != nil {
conn.Rollback()
}
fmt.Printf("begin failed, err:%v\n", err)
return
} sqlstr := "update user set age = 1 where id = ?"
_, err = conn.Exec(sqlstr, )
if err != nil {
conn.Rollback()
fmt.Printf("exec sql:%s failed, err:%v\n", sqlstr, err)
return
} sqlstr = "update user set age = 2 where id = ?"
_, err = conn.Exec(sqlstr, )
if err != nil {
conn.Rollback()
fmt.Printf("exec second sql:%s failed, err:%v\n", sqlstr, err)
return
}
err = conn.Commit()
if err != nil {
fmt.Printf("commit failed, err:%v\n", err)
conn.Rollback()
return
}
} func main() {
err := initDb()
if err != nil {
fmt.Printf("init db failed, err:%v\n", err)
return
} //testQueryData()
//testQueryMultilRow()
//testInsertData()
//testUpdateData()
//testDeleteData()
//testPrepareData()
//testPrepareInsertData()
testTrans()
}
package main

import (
"database/sql"
"fmt" _ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
) var DB *sqlx.DB func initDb() error {
var err error
dsn := "root:root@tcp(localhost:3306)/golang_db"
DB, err = sqlx.Open("mysql", dsn)
if err != nil {
return err
} DB.SetMaxOpenConns()
DB.SetMaxIdleConns()
return nil
} type User struct {
Id int64 `db:"id"`
Name sql.NullString `db:"name"`
Age int `db:"age"`
} func testQuery() {
sqlstr := "select id, name, age from user where id=?"
var user User err := DB.Get(&user, sqlstr, )
if err != nil {
fmt.Printf("get failed, err:%v\n", err)
return
} fmt.Printf("user:%#v\n", user)
} func testQueryMulti() {
sqlstr := "select id, name, age from user where id>?"
var user []User err := DB.Select(&user, sqlstr, )
if err != nil {
fmt.Printf("get failed, err:%v\n", err)
return
} fmt.Printf("user:%#v\n", user)
} func testUpdate() {
sqlstr := "update user set name=? where id=?"
result, err := DB.Exec(sqlstr, "abc", )
if err != nil {
fmt.Printf("update failed, err:%v\n", err)
return
}
count, err := result.RowsAffected()
if err != nil {
fmt.Printf("affected rows failed, err:%v\n", err)
return
}
fmt.Printf("affect rows:%d\n", count)
} func queryDB(name string) {
sqlstr := fmt.Sprintf("select id, name, age from user where name='%s'", name)
fmt.Printf("sql:%s\n", sqlstr)
var user []User
err := DB.Select(&user, sqlstr)
if err != nil {
fmt.Printf("select failed, err:%v\n", err)
return
} for _, v := range user {
fmt.Printf("user:%#v\n", v)
}
} func queryDBBySqlx(name string) {
sqlstr := "select id, name, age from user where name=?"
//fmt.Printf("sql:%s\n", sqlstr)
var user []User
err := DB.Select(&user, sqlstr, name)
if err != nil {
fmt.Printf("select failed, err:%v\n", err)
return
} for _, v := range user {
fmt.Printf("user:%#v\n", v)
}
} func testSqlInject() {
//queryDB("abc' or 1 = 1 #")
//queryDB("name=abc' and (select count(*) from user ) < 10#")
//queryDB("name=123' union select *from user #")
queryDBBySqlx("name=123' union select *from user #")
} func main() { err := initDb()
if err != nil {
fmt.Printf("init db failed, err:%v\n", err)
return
} //testQuery()
//testQueryMulti()
//testUpdate()
testSqlInject()
}

mysql_example的更多相关文章

随机推荐

  1. 用hexo在本地搭建自己的博客

    参考路径:https://blog.csdn.net/Hoshea_chx/article/details/78826689

  2. [JZOJ3187]【GDOI2013模拟8】的士

    题目 描述 题目大意 在一个数轴上,有些人要从某个点到达另一个点. 出租车从最左端出发,将所有人送到它们的目的地,最终到达最右边的点. 出租车只能做一个乘客,并且可以在图中将乘客丢下. 问最短时间. ...

  3. 【JZOJ3238】【BZOJ3482】超空间旅行

    description 在遥远的未来,行星之间的食品运输将依靠单向的贸易路线.每条路径直接连接两个行星,且其运输时间是已知的. 贸易商协会打算利用一项最近发现的新技术--超空间旅行,以增加一些新的航线 ...

  4. c++ static关键字的作用

    1.被申明的函数或值无法被其他源文件使用 2.static的第二个作用是保持变量内容的持久.(static变量中的记忆功能和全局生存期) 存储在静态数据区的变量会在程序刚开始运行时就完成初始化,也是唯 ...

  5. centos7的变化(转)

    centos7的变化 找了一个下午都不知道为什么找不到一些命令,终于在一个地方看到了. 地址:http://www.sa-log.com/276.html 王, 帅 2015年09月24日 于 运维日 ...

  6. 前端面试题之一JAVASCRIPT(算法类)

    一.JS操作获取和设置cookie //创建cookie function setcookie(name, value, expires, path, domain, secure) { var co ...

  7. MS-coco数据集下载及使用(转)

    先做个标记,改天研究下. 几个链接: MS coco数据集介绍及下载 Microsoft COCO 数据集 COCO Dataset 数据特点 COCO 数据集的使用

  8. iOS绘制线条的使用

    1.相关简介 1.1.iOS之UIBezierPath贝塞尔曲线属性简介 1.2.iOS之CAShapeLayer属性简介 2.绘制曲线 2.1.方法详解 - (void)addQuadCurveTo ...

  9. js如何往数组Array中添加元素 (2013-09-04 10

    unshift:将参数添加到原数组开头,并返回数组的长度 pop:删除原数组最后一项,并返回删除元素的值:如果数组为空则返回undefined push:将参数添加到原数组末尾,并返回数组的长度 co ...

  10. 2、设备树的规范(dts和dtb格式)

    第01节_DTS格式(1) 语法:Devicetree node格式:[label:] node-name[@unit-address] { [properties definitions]      ...