1. 程式人生 > 實用技巧 >[Go]GO語言實戰-GO-FLY線上客服gorm匯入sql檔案

[Go]GO語言實戰-GO-FLY線上客服gorm匯入sql檔案

當初始化專案的時候,之前需要手動匯入資料庫sql檔案,現在可以直接在命令列引數裡輸入go-fly install ,就可以把資料庫檔案導進去了

實現方式就是使用gorm執行sql檔案裡面的每行sql語句

讀入sql檔案後把字串按照分號分隔,轉成[]string ,然後再迴圈執行

例項程式碼是(自行更改檔案目錄):

func install(){
    sqlFile:=config.Dir+"go-fly.sql"
    isExit,_:=tools.IsFileExist(config.MysqlConf)
    dataExit,_:=tools.IsFileExist(sqlFile)
    
if !isExit||!dataExit{ fmt.Println("config/mysql.json 資料庫配置檔案或者資料庫檔案go-fly.sql不存在") os.Exit(1) } sqls,_:=ioutil.ReadFile(sqlFile) sqlArr:=strings.Split(string(sqls),";") for _,sql:=range sqlArr{ if sql==""{ continue } models.Execute(sql) } }

go-fly程式碼中資料庫操作類

package models

import (
    "fmt"
    "github.com/jinzhu/gorm"
    "github.com/taoshihan1991/imaptool/config"
    "time"
)
var DB *gorm.DB
type Model struct {
    ID        uint `gorm:"primary_key" json:"id"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"
updated_at"` DeletedAt *time.Time `sql:"index" json:"deleted_at"` } func init(){ mysql:=config.CreateMysql() dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysql.Username, mysql.Password, mysql.Server, mysql.Port, mysql.Database) DB,_=gorm.Open("mysql",dsn) DB.SingularTable(true) DB.LogMode(true) DB.DB().SetMaxIdleConns(10) DB.DB().SetMaxOpenConns(100) } func Execute(sql string){ DB.Exec(sql) } func CloseDB() { defer DB.Close() }

簡化的邏輯就是gorm open以後得到的例項執行一下Exec方法,執行sql語句

執行完成以後的效果: