安装
go get -u github.com/jinzhu/gorm
连接数据库
连接不同的数据库都需要导入对应数据的驱动程序,GORM
已经贴心的为我们包装了一些驱动程序,只需要按如下方式导入需要的数据库驱动即可:
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
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main() {
db, err := gorm.Open("mysql", "user:password@(localhost)/dbname?charset=utf8mb4&parseTime=True&loc=Local")
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
基本代码同上,注意引入对应sqlite
驱动并正确指定gorm.Open()
参数。
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
基本代码同上,注意引入对应mssql
驱动并正确指定gorm.Open()
参数。
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()
}
GORM基本示例
注意:
- 本文以MySQL数据库为例