标签归档:golang

RSS feed of golang

Golang:开源库 Go-MySQL-Driver 使用

Golang:开源库 Go-MySQL-Driver 使用

A MySQL-Driver for Go's database/sql package

MySQL

MySQL is the world's most popular open source database. Whether you are a fast growing web property, technology ISV or large enterprise, MySQL can cost-effectively help you deliver high performance, scalable database applications. —— MySQL

MySQL驱动 Go-MySQL-Driver 使用

github 地址

Go-MySQL-Driver

文档

Go-MySQL-Driver wiki

安装

$ go get -u github.com/go-sql-driver/mysql

导入

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

数据库表结构

USE test;
CREATE TABLE `squareNum` (
    `number` INT(11) NOT NULL DEFAULT '0',
    `squareNumber` INT(11) NOT NULL DEFAULT '0',
    PRIMARY KEY (`number`)
);
/*
+--------------+---------+------+-----+---------+-------+
| Field        | Type    | Null | Key | Default | Extra |
+--------------+---------+------+-----+---------+-------+
| number       | int(11) | NO   | PRI | NULL    |       |
| squareNumber | int(11) | NO   |     | NULL    |       |
+--------------+---------+------+-----+---------+-------+
*/

用例

package main

import (
        "database/sql"
        "fmt"
        _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "root:11111111@/test?charset=utf8")
    checkErr(err)
        defer db.Close()

    // Open doesn't open a connection. Validate DSN data:
    err = db.Ping()
    checkErr(err)

    // Use the DB normally, execute the querys etc
    stmtIns, err := db.Prepare("INSERT INTO squareNum VALUES( ?, ? )")
    checkErr(err)
    defer stmtIns.Close() // Close the statement when we leave main() / the program terminates

    stmtOut, err := db.Prepare("SELECT squareNumber FROM squareNum WHERE number = ?")
    checkErr(err)
    defer stmtOut.Close()
    for i := 0; i < 25; i++ {
                _, err = stmtIns.Exec(i, (i * i)) // Insert tuples (i, i^2)
                if err != nil {
                        panic(err.Error()) // proper error handling instead of panic in your app
                }
        }

    var squareNum int // we "scan" the result in here

    // Query the square-number of 13
        err = stmtOut.QueryRow(13).Scan(&squareNum) // WHERE number = 13
    checkErr(err)
    fmt.Printf("The square number of 13 is: %d\n", squareNum)

    // Query another number.. 1 maybe?
        err = stmtOut.QueryRow(1).Scan(&squareNum) // WHERE number = 1
        checkErr(err)
        fmt.Printf("The square number of 1 is: %d\n", squareNum)

    stmtIns, err = db.Prepare("DELETE FROM squareNum where number=?")
        checkErr(err)

    res, err := stmtIns.Exec(13)
        checkErr(err)

    affect, err := res.RowsAffected()
        checkErr(err)

    fmt.Println("affect:", affect)
}

func checkErr(err error) {
        if err != nil {
                panic(err.Error())
        }
}

/*
Output:
The square number of 13 is: 169
The square number of 1 is: 1
affect: 1
*/

以上

本文链接:/2018/06/21/golang-go-mysql-driver/
请尊重作者的劳动成果,转载请注明出处!Sakishum 博客保留对文章的所有权利。

Golang: 开源库 go-redis 使用

Redis

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. —— redis

开源库 go-redis 使用

github地址

go-redis

文档

go-redis doc

go-redis example

安装

go get -u github.com/go-redis/redis

导入

import "github.com/go-redis/redis"

用例

package main

import (
    "fmt"
    "github.com/go-redis/redis"
)

func main() {
    client := redis.NewClient(&redis.Options{
        Addr:     "127.0.0.1:6379",
        Password: "11111111",   // no password set
        DB:       0,            // use default DB
        })

        pong, err := client.Ping().Result()
    if err != nil {
        panic("Connect fail!")
    }
        fmt.Println(pong)

    err = client.Set("key", "value", 0).Err()
        if err != nil {
                panic(err)
        }

        val, err := client.Get("key").Result()
        if err != nil {
                panic(err)
        }
        fmt.Println("key", val)

        val2, err := client.Get("key2").Result()
        if err == redis.Nil {
                fmt.Println("key2 does not exist")
        } else if err != nil {
                panic(err)
        } else {
                fmt.Println("key2", val2)
        }
        // Output: key value
        // key2 does not exist
}

继续阅读

[goim]/usr/local/go/pkg/tool/linux_amd64/link: signal: killed

环境:

  • 腾讯云 1核1G
  • Linux VM_0_16_centos 3.10.0-693.11.6.el7.x86_64
  • gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
  • go version go1.9.4 linux/amd64

问题描述

这是什么鬼!?

# go install
go build goim/logic: /usr/local/go/pkg/tool/linux_amd64/link: signal: killed

从来没有见过这样的错误!!!

go build signal: killed #32

Google 之后再 github 找到了类似错误信息的讨论 https://github.com/beego/wetalk/issues/32

Just in case, this happened me few times when memory ran out. Usually when running go build/get in a VM with 512MB or less, or in docker container with limited and low RAM. ——korya commented on 12 Nov 2014

解决办法

原来是服务器上的内存都用快光了

# free -h
              total        used        free      shared  buff/cache   available
Mem:           992M        401M         73M        160M        517M        213M
Swap:            0B          0B          0B

把服务器上吃内存多的服务停掉, 例如 Kafka 。。。

释放内存到 512 M 内存以上了, go install 就成功了

总结

编译比较大型的 go 项目时内存空闲最好保持在 1GB 或更多 !!!! 7 (- 人 -)

Done.

本文链接:/2018/06/11/golangusrlocalgopkgtoollinux_amd64link-signal-killed/
请尊重作者的劳动成果,转载请注明出处!Sakishum 博客保留对文章的所有权利。