12

gobox中mysql操作

 4 years ago
source link: http://blog.7rule.com/2018/07/21/gobox-mysql.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

gobox中mysql操作

Jul 21, 2018

今天来说下使用gobox中mysql操作相关

本包的driver部分使用了go-sql-driver:https://github.com/go-sql-driver/mysql

示例表结构为:

| demo  | CREATE TABLE `demo` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `add_time` timestamp NOT NULL DEFAULT current_timestamp(),
  `edit_time` timestamp NOT NULL DEFAULT current_timestamp(),
  `name` varchar(20) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
  `status` tinyint(4) unsigned NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  KEY `status` (`status`),
  KEY `add_time` (`add_time`),
  KEY `edit_time` (`edit_time`)
) ENGINE=InnoDB AUTO_INCREMENT=478 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin |
package main

import (
	"github.com/goinbox/mysql"

	"database/sql"
	"strconv"
	"fmt"
)

type tableDemoRowItem struct {
	Id       int64
	AddTime  string
	EditTime string
	Name     string
	Status   int
}

var client *mysql.Client

func main() {
	config := mysql.NewConfig("root", "123", "127.0.0.1", "3306", "gobox-demo")
	client, _ = mysql.NewClient(config, nil)

	client.Exec("DELETE FROM demo")

	fmt.Println("testClientExec:")
	testClientExec()
	fmt.Println("")

	fmt.Println("testClientQuery:")
	testClientQuery()
	fmt.Println("")

	fmt.Println("testClientQueryRow:")
	testClientQueryRow()
	fmt.Println("")

	fmt.Println("testClientTrans:")
	testClientTrans()
	fmt.Println("")
}

func testClientExec() {
	result, err := client.Exec("INSERT INTO demo (name) VALUES (?),(?)", "a", "b")
	if err != nil {
		fmt.Println("exec error: " + err.Error())
	} else {
		li, err := result.LastInsertId()
		if err != nil {
			fmt.Println("lastInsertId error: " + err.Error())
		} else {
			fmt.Println("lastInsertId: " + strconv.FormatInt(li, 10))
		}

		rf, err := result.RowsAffected()
		if err != nil {
			fmt.Println("rowsAffected error: " + err.Error())
		} else {
			fmt.Println("rowsAffected: " + strconv.FormatInt(rf, 10))
		}
	}
}

func testClientQuery() {
	rows, err := client.Query("SELECT * FROM demo WHERE name IN (?,?)", "a", "b")
	if err != nil {
		fmt.Println("query error: " + err.Error())
	} else {
		for rows.Next() {
			item := new(tableDemoRowItem)
			err = rows.Scan(&item.Id, &item.AddTime, &item.EditTime, &item.Name, &item.Status)
			if err != nil {
				fmt.Println("rows scan error: " + err.Error())
			} else {
				fmt.Println(item)
			}
		}
	}
}

func testClientQueryRow() {
	row := client.QueryRow("SELECT * FROM demo WHERE name = ?", "a")
	item := new(tableDemoRowItem)
	err := row.Scan(&item.Id, &item.AddTime, &item.EditTime, &item.Name, &item.Status)
	if err != nil {
		if err == sql.ErrNoRows {
			fmt.Println("no rows: " + err.Error())
		} else {
			fmt.Println("row scan error: " + err.Error())
		}
	} else {
		fmt.Println(item)
	}
}

func testClientTrans() {
	client.Begin()

	row := client.QueryRow("SELECT * FROM demo WHERE name = ?", "a")
	item := new(tableDemoRowItem)
	err := row.Scan(&item.Id, &item.AddTime, &item.EditTime, &item.Name, &item.Status)
	if err != nil {
		fmt.Println("row scan error: " + err.Error())
	} else {
		fmt.Println(item)
	}

	client.Commit()

	err = client.Rollback()
	fmt.Println(err)
}

程序输出:

testClientExec:
lastInsertId: 474
rowsAffected: 2

testClientQuery:
&{474 2018-07-21 09:53:43 2018-07-21 09:53:43 a 0}
&{475 2018-07-21 09:53:43 2018-07-21 09:53:43 b 0}

testClientQueryRow:
&{474 2018-07-21 09:53:43 2018-07-21 09:53:43 a 0}

testClientTrans:
&{474 2018-07-21 09:53:43 2018-07-21 09:53:43 a 0}
Not in trans

ligang@vm-xubuntu ~/tmp/go $ go run main.go 
testClientExec:
lastInsertId: 476
rowsAffected: 2

testClientQuery:
&{476 2018-07-21 09:53:52 2018-07-21 09:53:52 a 0}
&{477 2018-07-21 09:53:52 2018-07-21 09:53:52 b 0}

testClientQueryRow:
&{476 2018-07-21 09:53:52 2018-07-21 09:53:52 a 0}

testClientTrans:
&{476 2018-07-21 09:53:52 2018-07-21 09:53:52 a 0}
Not in trans

欢迎大家使用,使用中有遇到问题随时反馈,我们会尽快响应,谢谢!


Recommend

  • 42
    • blog.7rule.com 6 years ago
    • Cache

    gobox中的连接池pool

    今天来说下gobox中的连接池底层实现pool 为什么需要连接池 我们的系统在访问外部资源(redis、mysql等)时,为了提高性能,通常会用到的一个优化方法就是把已经使用过的tcp连接保存起来,这样当需要再次使用时,就可...

  • 40
    • blog.7rule.com 6 years ago
    • Cache

    gobox中的log操作

    今天来说下使用gobox中的log操作 log级别定义 const ( LEVEL_EMERGENCY = 0 LEVEL_ALERT = 1 LEVEL_CRITICAL = 2 LEVEL_ERROR = 3 LEVEL_WARNING = 4 LEVEL_NOTICE = 5 LEVEL_INFO = 6...

  • 49
    • blog.7rule.com 6 years ago
    • Cache

    gobox中的http请求处理框架

    今天来说下使用gobox中的http请求处理框架 http请求处理架构图 重要的对象 System system用于实现g...

  • 39
    • blog.7rule.com 6 years ago
    • Cache

    gobox中的consumer处理框架

    我们都会有从异步队列中消费的需求,今天来说下gobox中的consumer处理框架 consumer处理架构图 重要的对象 IM...

  • 12
    • blog.7rule.com 4 years ago
    • Cache

    gobox中的常用工具包gomisc

    gobox中的常用工具包gomisc Sep 8, 2018 有一些常用的工具函数,我们把它们放到gomisc这个包中。 Slice中的值Unique func IntSliceUnique(s []int) []int func StringSli...

  • 13
    • blog.7rule.com 4 years ago
    • Cache

    gobox中的httpclient

    gobox中的httpclient Aug 18, 2018 今天来说下使用gobox中httpclient,这个包就相当于命令行的curl工具,用于发起http请求。 重要的对象 config const ( DEFAUL...

  • 16
    • blog.7rule.com 4 years ago
    • Cache

    gobox中的分页操作

    gobox中的分页操作 Aug 3, 2018 今天来说下使用gobox中的分页操作 分页也是我们开发时的一个常见需求,gobox中提供了page包做这个事情 package main import ( "github....

  • 17
    • blog.7rule.com 4 years ago
    • Cache

    gobox中redis操作

    gobox中redis操作 Jul 29, 2018 今天来说下使用gobox中redis操作相关 本包的driver部分使用了redigo:https://github.com/garyburd/redigo package main import ( "git...

  • 9
    • blog.7rule.com 4 years ago
    • Cache

    gobox中的simplecache和levelcache

    gobox中的simplecache和levelcache Jun 10, 2018 今天来说下gobox中的simplecache和levelcache simplecache simplecache提供了一个简单的内存kv package main i...

  • 13
    • blog.7rule.com 4 years ago
    • Cache

    gobox中的shardmap

    gobox中的shardmap May 25, 2018 今天来说下gobox中的shardmap。 golang中的map使用简单,但并发写入时,如果不加锁,会导致panic,所以性能很差。 shardmap就是为了解决这个问题,其核心思想就...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK