【Golang】Golang 连接 MySQL

Posted by 西维蜀黍 on 2020-01-12, Last Modified on 2021-09-21

安装

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

mysql数据库连接

  • 构建连接, 格式是:“用户名:密码@tcp(IP:端口)/数据库?charset=utf8”
  • 打开数据库,前者是驱动名,所以要导入: _ “github.com/go-sql-driver/mysql”
  • 设置数据库最大连接数和设置上数据库最大闲置连接数
  • 验证连接:使用Ping()函数
package main

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


//数据库配置
const (
	userName = "root"
	password = "123456"
	ip = "127.0.0.1"
	port = "3306"
	dbName = "test"
)

func InitDB()  {
  path := strings.Join([]string{userName, ":", password, "@tcp(",ip, ":", port, ")/", dbName, "?charset=utf8"}, "")
	db, error := gorm.Open("mysql", path)

	// if there is an error opening the connection, handle it
	if err != nil {
		panic(err.Error())
	}

	results, err := db.Query("select * from tb")
	fmt.Println(results)
	for results.Next() {
		var promotion Promotion
		// for each row, scan the result into our tag composite object
		err = results.Scan(&promotion.id, &promotion.c1, &promotion.c2)
		if err != nil {
			panic(err.Error()) // proper error handling instead of panic in your app
		}
	}
}

type Promotion struct {
	id int
	c1 string
	c2 string

}

func main() {
	InitDB()
}

Reference