1. 数据库 1.1. 连接数据库 要连接到数据库首先要导入驱动程序。例如
1 import  _  "github.com/go-sql-driver/mysql" 
 
为了方便记住导入路径,GORM包装了一些驱动。
1 2 3 4 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" 
 
1.1.1. MySQL 注:为了处理time.Time,您需要包括parseTime作为参数。 (更多支持的参数)
1 2 3 4 5 6 7 8 9 import  (     "github.com/jinzhu/gorm"      _ "github.com/jinzhu/gorm/dialects/mysql"  )func  main ()   {   db, err := gorm.Open("mysql" , "user:password@/dbname?charset=utf8&parseTime=True&loc=Local" )   defer  db.Close() }
 
1.1.2. PostgreSQL 1 2 3 4 5 6 7 8 9 import  (     "github.com/jinzhu/gorm"      _ "github.com/jinzhu/gorm/dialects/postgres"  )func  main ()   {   db, err := gorm.Open("postgres" , "host=myhost user=gorm dbname=gorm sslmode=disable password=mypassword" )   defer  db.Close() }
 
1.1.3. Sqlite3 1 2 3 4 5 6 7 8 9 import  (     "github.com/jinzhu/gorm"      _ "github.com/jinzhu/gorm/dialects/sqlite"  )func  main ()   {   db, err := gorm.Open("sqlite3" , "/tmp/gorm.db" )   defer  db.Close() }
 
1.1.4. 不支持的数据库 GORM正式支持上述的数据库,如果您使用的是不受支持的数据库请按照链接 编写对应数据库支持文件。
1.2. 迁移 1.2.1. 自动迁移 自动迁移模式将保持更新到最新。
警告 :自动迁移仅仅会创建表、缺少列和索引,并且不会改变现有列的类型或删除未使用的列以保护数据。
1 2 3 4 5 6 db.AutoMigrate(&User{}) db.AutoMigrate(&User{}, &Product{}, &Order{}) db.Set("gorm:table_options" , "ENGINE=InnoDB" ).AutoMigrate(&User{})
 
1.2.2. 检查表是否存在 1 2 3 4 5  db.HasTable(&User{}) db.HasTable("users" )
 
1.2.3. 创建表 1 2 3 4 5  db.CreateTable(&User{}) db.Set("gorm:table_options" , "ENGINE=InnoDB" ).CreateTable(&User{})
 
1.2.4. 删除表 1 2 3 4 5 6 7 8  db.DropTable(&User{}) db.DropTable("users" ) db.DropTableIfExists(&User{}, "products" )
 
1.2.5. 修改列 修改列的类型为给定值
1 2  db.Model(&User{}).ModifyColumn("description" , "text" )
 
1.2.6. 删除列 1 2  db.Model(&User{}).DropColumn("description" )
 
1.2.7. 添加外键 1 2 3 4 5 6  db.Model(&User{}).AddForeignKey("city_id" , "cities(id)" , "RESTRICT" , "RESTRICT" )
 
PS:
1 2 3 4 5 6 在设置外键的时候,删除时和更新时两列有四个值可以选择:CASCADE、NO ACTION、RESTRICT、SET NULL,自己全亲自试了一遍,它们的区别如下: CASCADE:父表delete 、update的时候,子表会delete 、update掉关联记录; SET NULL:父表delete 、update的时候,子表会将关联记录的外键字段所在列设为null,所以注意在设计子表时外键不能设为not null; RESTRICT:如果想要删除父表的记录时,而在子表中有关联该父表的记录,则不允许删除父表中的记录; NO ACTION:同 RESTRICT,也是首先先检查外键;
 
1.2.8. 索引 1 2 3 4 5 6 7 8 9 10 11 12 13 14  db.Model(&User{}).AddIndex("idx_user_name" , "name" ) db.Model(&User{}).AddIndex("idx_user_name_age" , "name" , "age" ) db.Model(&User{}).AddUniqueIndex("idx_user_name" , "name" ) db.Model(&User{}).AddUniqueIndex("idx_user_name_age" , "name" , "age" ) db.Model(&User{}).RemoveIndex("idx_user_name" )