GORM基本使用

2022-07-23 03:00:16 字數 2469 閱讀 1171

目錄

go get -u github.com/jinzhu/gorm
要連線資料庫首先要匯入驅動程式

// gorm已經包裝了一些驅動

// import _ "github.com/jinzhu/gorm/dialects/mssql"

// 資料庫連線

func main()

// 2. postgresql

db2, err := gorm.open("postgres", "host=myhost user=gorm dbname=gorm sslmodel=disable password=password")

defer db2.close()

// 3. sqlite3

db3, err := gorm.open("sqlite3", "/tmp/gorm.db")

defer db3.close()

}

gorm正式支援上述的資料庫,如果您使用的是不受支援的資料庫請按照本鏈結中的要求編寫對應資料庫支援檔案。

// 資料庫遷移

func main()

db.automigrate(&user{})

&product{}, &order{})

// 建立表時新增表字尾

"gorm:table_options", "engine=innodb").automigrate(&user{})

// 2. 檢查表是否存在

// 2.1 檢查模型`user`是否存在

db.hastable(&user{})

// 2.2 檢查表`user`是否存在

db.hastable("user")

// 3. 建立表

// 3.1 為模型`user`建立表

db.createtable(&user{})

// 3.2 建立表時將"engine=innodb"附加到sql語句

db.set("gorm:table_options", "engine=innodb").createtable(&user{})

// 4. 刪除表

// 4.1 刪除模型`user`的表

db.droptable(&user{})

// 4.2 刪除表user

db.droptable("user")

// 4.3 刪除刪除模型`user`的表和表`products`

db.droptable(&user{}, "products")

// 5. 修改列

// 修改模型`user`的description列的資料型別為`text`

db.model(&user{}).modifycolumn("description", "text")

// 6. 刪除列

// 刪除模型`user·的description列

db.model(&user{}).dropcolumn("description")

// 7. 新增外來鍵

// 新增主鍵

// 1st param : 外來鍵字段

// 2nd param : 外來鍵表(字段)

// 3rd param : ondelete

// 4th param : onupdate

db.model(&user{}).addforeignkey("city_id", "cities(id)", "restrict", "restrict")

// 8. 索引

// 8.1 為`name`列新增索引`idx_user_anme`

db.model(&user{}).addindex("idx_user_name", "name")

// 8.2 為`name`,`age`列新增索引`idx_user_name_age`

db.model(&user{}).addindex("idx_user_name_age", "name", "age")

// 8.3 新增唯一索引

db.model(&user{}).adduniqueindex("idx_user_name", "name")

// 8.4 為多列新增唯一索引

db.model(&user{}).adduniqueindex("idx_user_name_age", "name", "age")

// 8.5 刪除索引

db.model(&user{}).removeindex("idx_user_name")

}

gorm快速使用

模型 為表中的字段,記得欄位名開頭大寫 type patient struct 此例為postgresql func main 不重新建立複數結尾的表,還是原來的表,可以利用原表中的結構,資料 db.singulartable true defer db.close 建立 patient db.cr...

go語言gorm使用

var jsondata map string inte ce 全域性變數 存放配置檔案的map物件 func initjson configstr string bytes reg regexp.mustcompile configstr reg.replaceallstring configst...

gorm使用和例項封裝

三 gorm資料庫連線例項封裝 建立 db.create product 讀取 var product product db.first product,1 查詢id為1的product db.first product,code l1212 查詢code為l1212的product 更新 更新pr...