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. [记]Windows 系统下设置Nodejs NPM全局路径

    Windows下的Nodejs npm路径是appdata,担心安装的node_modules越来越多,导致C盘满,所以参考别人的博文,将node_modules安装的默认目录修改一下. 参考Wind ...

  2. ros python

    https://www.ncnynl.com/archives/201611/1059.html python的节点需要对节点设置权限为可执行,在.py文件所在的路径执行如下命令 $ touch ta ...

  3. duilib教程之duilib入门简明教程4.响应按钮事件

    上一个Hello World的教程里有一句代码是这样的:CControlUI *pWnd = new CButtonUI;    也就是说,其实那整块绿色背景区域都是按钮的区域.(这里简要介绍下,CC ...

  4. 深入浅出Mybatis系列(二)---配置简介(mybatis源码篇)[转]

    上篇文章<深入浅出Mybatis系列(一)---Mybatis入门>, 写了一个Demo简单体现了一下Mybatis的流程.本次,将简单介绍一下Mybatis的配置文件: 上次例子中,我们 ...

  5. jeecms v9库内新增对象的流程及其他技巧

    cms 开发 ———— 库内新增对象 Products 的流程说明及其他技巧 第一步:Entity com.jeecms.cms.entity.assist.base下建立模型基础类BaseCmsPr ...

  6. 转:shell笔试题

    源地址:http://blog.csdn.net/zcsylj/article/details/6799632 1.用Shell编程,判断一文件是不是块或字符设备文件,如果是将其拷贝到 /dev 目录 ...

  7. shell脚本实现读取一个文件中的某一列,并进行循环处理

    shell脚本实现读取一个文件中的某一列,并进行循环处理 1) for循环 #!bin/bash if [ ! -f "userlist.txt" ]; then echo &qu ...

  8. python 之 字符串处理

    分割字符串 根据某个分割符分割 >>> a = '1,2,3,4' >>> a.split(',') ['] 根据多个分隔符分割 >>> line ...

  9. <每日一题>题目6:二分查找

    #二分查找 ''' 1.end问题 2.44对应的end<start 找不到情况 3.返回值递归的情况 4,611,aim太大的情况 ''' l = [2,3,5,10,15,16,18,22, ...

  10. jmeter参数化之用户参数

    1.     用badboby进行录制,录制完成后保存,用JMeter格式进行保存,如:登陆.jmx 2.     在jmeter中打开保存的文件登陆.jmx. 3.在step1上右击-添加-前置处理 ...