日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

golang?gorm框架數(shù)據(jù)庫的連接操作示例_Golang

作者:Jeff的技術(shù)棧 ? 更新時間: 2022-06-15 編程語言

1. 連接數(shù)據(jù)庫

要連接到數(shù)據(jù)庫首先要導(dǎo)入驅(qū)動程序。例如

import _ "github.com/go-sql-driver/mysql"

為了方便記住導(dǎo)入路徑,GORM包裝了一些驅(qū)動。

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作為參數(shù)。 (更多支持的參數(shù))

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

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

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 不支持的數(shù)據(jù)庫

GORM正式支持上述的數(shù)據(jù)庫,如果您使用的是不受支持的數(shù)據(jù)庫請按照下面的連接編寫對應(yīng)數(shù)據(jù)庫支持文件。?https://github.com/jinzhu/gorm/blob/master/dialect.go

2. 遷移

2.1. 自動遷移

自動遷移模式將保持更新到最新。

警告:自動遷移僅僅會創(chuàng)建表,缺少列和索引,并且不會改變現(xiàn)有列的類型或刪除未使用的列以保護數(shù)據(jù)。

db.AutoMigrate(&User{})
db.AutoMigrate(&User{}, &Product{}, &Order{})
// 創(chuàng)建表時添加表后綴
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})

2.2. 檢查表是否存在

// 檢查模型`User`表是否存在
db.HasTable(&User{})
// 檢查表`users`是否存在
db.HasTable("users")

2.3. 創(chuàng)建表

// 為模型`User`創(chuàng)建表
db.CreateTable(&User{})
// 創(chuàng)建表`users'時將“ENGINE = InnoDB”附加到SQL語句
db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&User{})

2.4. 刪除表

// 刪除模型`User`的表
db.DropTable(&User{})
// 刪除表`users`
db.DropTable("users")
// 刪除模型`User`的表和表`products`
db.DropTableIfExists(&User{}, "products")

2.5. 修改列

修改列的類型為給定值

// 修改模型`User`的description列的數(shù)據(jù)類型為`text`
db.Model(&User{}).ModifyColumn("description", "text")

2.6. 刪除列

// 刪除模型`User`的description列
db.Model(&User{}).DropColumn("description")

2.7. 添加外鍵

// 添加主鍵
// 1st param : 外鍵字段
// 2nd param : 外鍵表(字段)
// 3rd param : ONDELETE
// 4th param : ONUPDATE
db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")

2.8. 索引

// 為`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")

原文鏈接:https://www.cnblogs.com/guyouyin123/p/14109856.html

欄目分類
最近更新