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 MySQL
注:为了处理time.Time
,您需要包括parseTime
作为参数。 (更多支持的参数)
1
2
3
4
5
6
7
8
|
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.2 PostgreSQL
1
2
3
4
5
6
7
8
|
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.3 Sqlite3
1
2
3
4
5
6
7
8
|
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.4 不支持的数据库
GORM正式支持上述的数据库,如果您使用的是不受支持的数据库请按照下面的连接编写对应数据库支持文件。 https://github.com/jinzhu/gorm/blob/master/dialect.go
2. 迁移
2.1. 自动迁移
自动迁移模式将保持更新到最新。
警告:自动迁移仅仅会创建表,缺少列和索引,并且不会改变现有列的类型或删除未使用的列以保护数据。
1
2
3
4
|
db.AutoMigrate(&User{}) db.AutoMigrate(&User{}, &Product{}, &Order{}) // 创建表时添加表后缀 db.Set( "gorm:table_options" , "ENGINE=InnoDB" ).AutoMigrate(&User{}) |
2.2. 检查表是否存在
1
2
3
4
|
// 检查模型`User`表是否存在 db.HasTable(&User{}) // 检查表`users`是否存在 db.HasTable( "users" ) |
2.3. 创建表
1
2
3
4
|
// 为模型`User`创建表 db.CreateTable(&User{}) // 创建表`users'时将“ENGINE = InnoDB”附加到SQL语句 db.Set( "gorm:table_options" , "ENGINE=InnoDB" ).CreateTable(&User{}) |
2.4. 删除表
1
2
3
4
5
6
|
// 删除模型`User`的表 db.DropTable(&User{}) // 删除表`users` db.DropTable( "users" ) // 删除模型`User`的表和表`products` db.DropTableIfExists(&User{}, "products" ) |
2.5. 修改列
修改列的类型为给定值
1
2
|
// 修改模型`User`的description列的数据类型为`text` db.Model(&User{}).ModifyColumn( "description" , "text" ) |
2.6. 删除列
1
2
|
// 删除模型`User`的description列 db.Model(&User{}).DropColumn( "description" ) |
2.7. 添加外键
1
2
3
4
5
6
|
// 添加主键 // 1st param : 外键字段 // 2nd param : 外键表(字段) // 3rd param : ONDELETE // 4th param : ONUPDATE db.Model(&User{}).AddForeignKey( "city_id" , "cities(id)" , "RESTRICT" , "RESTRICT" ) |
2.8. 索引
1
2
3
4
5
6
7
8
9
10
|
// 为`name`列添加索引`idx_user_name` db.Model(&User{}).AddIndex( "idx_user_name" , "name" ) // 为`name`, `age`列添加索引`idx_user_name_age` 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" ) |
以上就是golang gorm框架数据库操作示例的详细内容,更多关于golang gorm框架数据库操作的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/guyouyin123/p/14109856.html