连接数据库
为了连接数据库,你首先要导入数据库驱动程序。例如:
Go
import _ "github.com/go-sql-driver/mysql"
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
GORM 已经包含了一些驱动程序,为了方便的去记住它们的导入路径,你可以像下面这样导入
mysql 驱动程序
Go
import _ "github.com/jinzhu/gorm/dialects/mysql"
// import _ "github.com/jinzhu/gorm/dialects/postgres"
// import _ "github.com/jinzhu/gorm/dialects/sqlite"
// import _ "github.com/jinzhu/gorm/dialects/mssql"
支持的数据库
MySQL
注意: 为了正确的处理 time.Time ,你需要包含 parseTime 作为参数。 (More supported parameters)
Go
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main() {
db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=Tr
ue&loc=Local")
defer db.Close()
}
PostgreSQL
Go
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
Go
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
Get started with SQL Server,它可以通过 Docker 运行在你的 Mac, Linux 上。
Go
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mssql"
)
func main() {
db, err := gorm.Open("mssql", "sqlserver://username:password@localhost:1433?da
tabase=dbname")
defer db.Close()
}
不支持的数据库
GORM 官方支持以上四种数据库, 你可以为不支持的数据库编写支持,参考 GORM Dialects