1. 连接数据库

    为了连接数据库,你首先要导入数据库驱动程序。例如:

    1. // import _ "github.com/jinzhu/gorm/dialects/postgres"
    2. // import _ "github.com/jinzhu/gorm/dialects/mssql"

    注意: 为了正确的处理 time.Time ,你需要包含 parseTime 作为参数。 ()

    1. import (
    2. "github.com/jinzhu/gorm"
    3. )
    4. func main() {
    5. db, err := gorm.Open("postgres", "host=myhost port=myport user=gorm dbname=gorm password=mypassword")
    6. defer db.Close()
    1. import (
    2. _ "github.com/jinzhu/gorm/dialects/mssql"
    3. )
    4. func main() {
    5. db, err := gorm.Open("mssql", "sqlserver://username:password@localhost:1433?database=dbname")
    6. defer db.Close()
    7. }

    GORM 官方支持以上四种数据库, 你可以为不支持的数据库编写支持,参考 GORM Dialects