安装
$ 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
FEATURED TAGS
algorithm
algorithmproblem
architecturalpattern
architecture
aws
c#
cachesystem
codis
compile
concurrentcontrol
database
dataformat
datastructure
debug
design
designpattern
distributedsystem
django
docker
domain
engineering
freebsd
git
golang
grafana
hackintosh
hadoop
hardware
hexo
http
hugo
ios
iot
java
javaee
javascript
kafka
kubernetes
linux
linuxcommand
linuxio
lock
macos
markdown
microservices
mysql
nas
network
networkprogramming
nginx
node.js
npm
oop
openwrt
operatingsystem
padavan
performance
programming
prometheus
protobuf
python
redis
router
security
shell
software testing
spring
sql
systemdesign
truenas
ubuntu
vmware
vpn
windows
wmware
wordpress
xml
zookeeper