Go语言中访问MySql

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

首先安装mysql的go语言驱动
go get github.com/ziutek/mymysql/godrv
演示代码
package users
 
import (
    "database/sql" 
    "fmt"
    _ "github.com/ziutek/mymysql/godrv"
)
 
const (
    DB_NAME = "mysql_database_name"
    DB_USER = "mysql_user"
    DB_PASS = "mysql_password"
)
 
type User struct {
    Id      int    `json:"id"`
    Name string `json:"name"`
    Alias   string `json:"alias"`
}
 
func OpenDB() *sql.DB {
    db, err := sql.Open("mymysql", fmt.Sprintf("%s/%s/%s", DB_NAME, DB_USER, DB_PASS))
    if err != nil {
        panic(err)
    }
    return db
}
 
func UserById(id int) User {
    db := OpenDB()
    defer db.Close()
    row := db.QueryRow("SELECT `id`, `name`,`alias` FROM `users` WHERE id=?", id)
    user := new(User)
    row.Scan(&user.Id, &user.Name, &user.Alias)
    return user
}