使用GORM连接各种数据库
1.概述
gorm是一个使用Go语言编写的ORM框架。它文档齐全,对开发者友好,支持主流数据库。
安装:
go get -u github.com/jinzhu/gorm
2.连接数据库
连接不同的数据库都需要导入对应数据的驱动程序,GORM已经贴心的为我们包装了一些驱动程序,只需要按如下方式导入需要的数据库驱动即可:
GORM 官方支持的数据库类型有: MySQL, PostgreSQL, SQlite, SQL Server
连接Mysql
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main() {
db, err := gorm.Open("mysql", "root:root@(localhost)/gorm-test?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
fmt.Println("发生错误!", err)
}
defer db.Close()
}
连接PostgreSQL
基本代码同上,注意引入对应postgres驱动并正确指定gorm.Open()
参数
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
func main() {
db, err := gorm.Open("postgres", "host=myhost port=myport user=gorm dbname=gorm password=mypassword")
defer db.Close()
}
连接Sqlite3
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
func main() {
db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
defer db.Close()
}
连接SQL Server
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mssql"
)
func main() {
db, err := gorm.Open("mssql", "sqlserver://username:password@localhost:1433?database=dbname")
defer db.Close()
}
3.连接池
GORM 使用 database/sql
维护连接池
sqlDB, err := db.DB()
// SetMaxIdleConns 设置空闲连接池中连接的最大数量
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(time.Hour)