安装

  1. go get -u github.com/go-gorm/gorm

这里项目源码是 github.com/go-gorm/gorm

安装地址是 github.com/jinzhu/gorm

连接数据库

引入驱动

  1. import _ "github.com/jinzhu/gorm/dialects/mysql"
  2. // import _ "github.com/jinzhu/gorm/dialects/postgres"
  3. // import _ "github.com/jinzhu/gorm/dialects/sqlite"
  4. // import _ "github.com/jinzhu/gorm/dialects/mssql"

mysql

  1. import (
  2. "github.com/jinzhu/gorm"
  3. _ "github.com/jinzhu/gorm/dialects/mysql"
  4. )
  5. func main() {
  6. // db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
  7. // user:password@(localhost)/dbname?charset=utf8&parseTime=True&loc=Local
  8. db, err := DbOpen("mysql", "root:123456@(127.0.0.1:3306)/stbtest?charset=utf8")
  9. defer db.Close()
  10. }

PostgreSQL

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

SQLite3

  1. import (
  2. "github.com/jinzhu/gorm"
  3. _ "github.com/jinzhu/gorm/dialects/sqlite"
  4. )
  5. func main() {
  6. db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
  7. defer db.Close()
  8. }

SQL Server

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