首頁 後端開發 Golang 介紹golang gorm操作mysql及gorm基本用法

介紹golang gorm操作mysql及gorm基本用法

May 17, 2021 pm 04:45 PM
golang gorm mysql

以下由golang教學欄位來介紹golang gorm操作mysql及gorm基本用法,希望對需要的朋友有幫助!

golang 官方的那個操作mysql的有點麻煩所以就使用了gorm,下面就gorm的使用做下簡單介紹

#下載gorm:

go get -u github.com/jinzhu/gorm

在專案中引入gorm:

import (
 "github.com/jinzhu/gorm"
 _ "github.com/jinzhu/gorm/dialects/mysql"
)
登入後複製

定義db連接資訊

func DbConn(MyUser, Password, Host, Db string, Port int) *gorm.DB {
 connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", MyUser,Password, Host, Port, Db )
 db, err := gorm.Open("mysql", connArgs)
 if err != nil {
  log.Fatal(err)
 }
 db.SingularTable(true)
 return db
}
登入後複製

由於grom是使用的orm映射,所以需要定義要操作的表的model,在go中需要定義一個struct, struct的名字就是對應資料庫中的表名,注意gorm查找struct名對應資料庫中的表名的時候會預設把你的struct中的大寫字母轉換為小寫並加上“s”,所以可以加上db.SingularTable(true) 讓grom轉義struct名字的時候不用加上s。我是提前在資料庫中創建好表的然後再用grom去查詢的,也可以用gorm去創建表,我感覺還是直接在數據庫上創建,修改表字段的操作方便,grom只用來查詢和更新數據。

假設資料庫中的表格已經建立好,下面是資料庫中的建表語句:

CREATE TABLE `xz_auto_server_conf` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `group_zone` varchar(32) NOT NULL COMMENT '大区例如:wanba,changan,aiweiyou,360',
 `server_id` int(11) DEFAULT '0' COMMENT '区服id',
 `server_name` varchar(255) NOT NULL COMMENT '区服名称',
 `open_time` varchar(64) DEFAULT NULL COMMENT '开服时间',
 `service` varchar(30) DEFAULT NULL COMMENT '环境,test测试服,formal混服,wb玩吧',
 `username` varchar(100) DEFAULT NULL COMMENT 'data管理员名称',
 `submit_date` datetime DEFAULT NULL COMMENT '记录提交时间',
 `status` tinyint(2) DEFAULT '0' COMMENT '状态,0未处理,1已处理,默认为0',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
登入後複製

定義model,即struct, 定於struct時我們可以只定義我們需要從資料庫取回的特定欄位:

gorm在轉義表名的時候會把stuct的大寫字母(首字母除外) 替換成“_”,所以下面的"XzAutoServerConf "會轉義成數資料庫中對應「xz_auto_server conf」的表名, 對應的字段名的查找會先按照tag裡面的名稱去裡面查找,如果沒有定義標籤則按照struct定義的字段查找,查找的時候struct字段中的大寫會被轉義成“ ”,例“GroupZone”會去查找表中的group_zone字段

//定义struct
type XzAutoServerConf struct {
 GroupZone string `gorm:"column:group_zone"`
 ServerId int
 OpenTime string
 ServerName string
 Status int
}
登入後複製
//定义数据库连接
type ConnInfo struct {
 MyUser string
 Password string
 Host string
 Port int
 Db string
}

func main () {
cn := ConnInfo{
  "root",
  123456",
  "127.0.0.1",
  3306,
  "xd_data",
 }
  db := DbConn(cn.MyUser,cn.Password,cn.Host,cn.Db,cn.Port)
  defer db.Close() // 关闭数据库链接,defer会在函数结束时关闭数据库连接
 var rows []api.XzAutoServerConf
//select 
db.Where("status=?", 0).Select([]string{"group_zone", "server_id", "open_time", "server_name"}).Find(&rows)
//update
 err := db.Model(&rows).Where("server_id=?", 80).Update("status", 1).Error
 if err !=nil {
 fmt.Println(err)
 }
fmt.Println(rows)
}
登入後複製

更多grom操作可以參考:https://jasperxu.github.io/gorm-zh/

下面看下Golang GORM使用

#gorm

##gorm是go語言中實作資料庫存取的ORM(物件關聯映射)庫。使用這個函式庫,我們可以利用物件導向的方法,更方便的對資料庫中的資料進行CRUD(增刪改查)。

基本上使用

下載依賴

go get github.com/jinzhu/gorm
go get github.com/go-sql-driver/mysql
登入後複製

第一個是核心庫。


第二個是mysql驅動包。

連接資料庫

packae main
import (
 "github.com/jinzhu/gorm"
 _ "github.com/jinzhu/gorm/dialects/mysql"
 "fmt"
)
func main() {
 db, err := gorm.Open("mysql",
 "root:root@/test?charset=utf8&parseTime=True&loc=Local")

 if err != nil {
  fmt.Println(err)
  return
 }else {
  fmt.Println("connection succedssed")
 }
 defer db.Close()
登入後複製

新增資料

type User struct {
 ID  int   `gorm:"primary_key"`
 Name string   `gorm:"not_null"`
}
func add() {
 user := &User{Name:"zhangsan"}
 db.Create(user)
}
登入後複製

刪除資料

user := &User{ID:1}
db.delete(user)
登入後複製

更新資料

user := &User{ID:1}
db.Model(user).update("Name","lisi")
登入後複製

查詢資料

// query all
var users []User
db.Find(&users)
fmt.Println(users)
// query one
user := new (User)
db.First(user,1)
fmt.Println(user)
登入後複製

其它

判斷資料庫中是否有結構體對應的表格:

db.HasTable(User{})
登入後複製

建立表格

db.CreateTable(User{})
登入後複製
以上就是gorm基本的用法。

以上是介紹golang gorm操作mysql及gorm基本用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何使用 Golang 安全地讀取和寫入檔案? 如何使用 Golang 安全地讀取和寫入檔案? Jun 06, 2024 pm 05:14 PM

如何使用 Golang 安全地讀取和寫入檔案?

如何為 Golang 資料庫連線配置連線池? 如何為 Golang 資料庫連線配置連線池? Jun 06, 2024 am 11:21 AM

如何為 Golang 資料庫連線配置連線池?

如何修復 MySQL 8.4 上的 mysql_native_password 未載入錯誤 如何修復 MySQL 8.4 上的 mysql_native_password 未載入錯誤 Dec 09, 2024 am 11:42 AM

如何修復 MySQL 8.4 上的 mysql_native_password 未載入錯誤

golang框架的優缺點比較 golang框架的優缺點比較 Jun 05, 2024 pm 09:32 PM

golang框架的優缺點比較

Golang 框架中的錯誤處理最佳實務有哪些? Golang 框架中的錯誤處理最佳實務有哪些? Jun 05, 2024 pm 10:39 PM

Golang 框架中的錯誤處理最佳實務有哪些?

golang框架開發實戰詳解:問題答疑 golang框架開發實戰詳解:問題答疑 Jun 06, 2024 am 10:57 AM

golang框架開發實戰詳解:問題答疑

如何在 Golang 中將 JSON 資料保存到資料庫中? 如何在 Golang 中將 JSON 資料保存到資料庫中? Jun 06, 2024 am 11:24 AM

如何在 Golang 中將 JSON 資料保存到資料庫中?

Golang框架與Go框架:內部架構與外部特性對比 Golang框架與Go框架:內部架構與外部特性對比 Jun 06, 2024 pm 12:37 PM

Golang框架與Go框架:內部架構與外部特性對比

See all articles