golang Gorm執行原生SQL

/// 連接數據庫得到
func GetConn() (*gorm.DB,error) {
    db,err :=gorm.Open("mysql","root:[email protected](127.0.0.1:3306)/mytest?charset=utf8mb4&parseTime=True&loc=Local")
    return db,err
}
package createtable

import (
    "GinMysql/dbhelper"
    "GinMysql/model"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    "log"
)

func init(){
    var user model.User
    var userinfo model.UserInfo
    db,err := dbhelper.GetConn()
    if err!=nil{
        log.Panicln("連接數據庫出錯:",err)
    }
    // 數據遷移 到Mysql
    db.AutoMigrate(&user)
    db.AutoMigrate(&userinfo)

}
package main

import (
    // 引用 createtable 調用init方法
    _ "GinMysql/createtable"
    "GinMysql/route"
)


func main(){
    engin:= route.SetUpRoute()
    engin.Run(":8090")
}
type Mycount struct {
    Usercount uint
}

 

    //  關於Gorm執行原生SQL
    // **********語句字段要小寫************
    // ***********查詢用db.Raw,其他用db.Exec
    // *********** 字段大小寫要對應上 **************
    // *************** 注意要 defer rows.Close()
    var Mycount Mycount
    rows,_:= db.Debug().Raw("select Count(1) as Usercount from Users").Rows()
    defer rows.Close()
    for rows.Next() {
        rows.Scan(&Mycount.Usercount)
    }
    var users []User
    //   查詢 執行用Scan 和Find 一樣
    db=db.Raw("select uid,user_name,age from Users").Scan(&users)
    //db=db.Raw("select uid,user_name,age from Users").Find(&users)
    fmt.Println("Users",users)
    //  更新和刪除.插入用 Exec
    db= db.Exec("update Users set user_name='def' where uid=?",1)
    fmt.Println("更新了",db.RowsAffected,"條數據")
    db= db.Exec("delete from Users where uid=?",2)
    fmt.Println("更新了",db.RowsAffected,"條數據")
    return  int32(Mycount.Usercount)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章