1. 连接数据库
为了连接数据库,你首先要导入数据库驱动程序。例如:
// import _ "github.com/jinzhu/gorm/dialects/postgres"
// import _ "github.com/jinzhu/gorm/dialects/mssql"
注意: 为了正确的处理 time.Time
,你需要包含 parseTime
作为参数。 ()
import (
"github.com/jinzhu/gorm"
)
func main() {
db, err := gorm.Open("postgres", "host=myhost port=myport user=gorm dbname=gorm password=mypassword")
defer db.Close()
import (
_ "github.com/jinzhu/gorm/dialects/mssql"
)
func main() {
db, err := gorm.Open("mssql", "sqlserver://username:password@localhost:1433?database=dbname")
defer db.Close()
}
GORM 官方支持以上四种数据库, 你可以为不支持的数据库编写支持,参考 GORM Dialects