dsfdsfdsfdsf1223 2019-02-16 04:53
浏览 119
已采纳

如何显示查询结果

I'm working on a RESTful API project, and I have problem that my code can query with gorm, my query like this countSequenceId := db.Debug().Raw("SELECT COUNT (*) FROM SMSBlast2").Scan(&smsblast1). I have the result [1 rows affected or returned], that mean success to count my all row in database , but I want to display the result like result count = 10, but how?

Image

 package main

import (
    "encoding/json"
    "fmt"
    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mssql"
    "log"
    "net/http"
    "strconv"
    "time"
)

type SMSBlast struct {
    SequenceID   int `gorm:"primary_key";column:"SequenceID"`
    MobilePhone string `gorm:"column:MobilePhone"`
    Output  string  `gorm:"column:Output"`
    WillBeSentDate *time.Time `gorm:"column:WillBeSentDate"`
    SentDate *time.Time `gorm:"column:SentDate"`
    Status *string `gorm:"column:Status"`
    DtmUpd time.Time `gorm:"column:DtmUpd"`
}

func (SMSBlast) TableName() string {
    return "SMSBlast2"
}

func allSMSBlasts(w http.ResponseWriter, r *http.Request){
    db, err := gorm.Open("mssql", "sqlserver://sa:@localhost:1433?database=CONFINS")
    if err != nil{
        panic("failed to connect database")
    }
    defer db.Close()

    var smsblasts []SMSBlast
    db.Debug().Find(&smsblasts)
    fmt.Println("{}",smsblasts)

    json.NewEncoder(w).Encode(smsblasts)
}

func insertSMSBlast(w http.ResponseWriter, r *http.Request){
    fmt.Println("New Insert Created")

    db, err := gorm.Open("mssql", "sqlserver://sa:@localhost:1433?database=CONFINS")
    if err != nil{
        panic("failed to connect database")
    }
    defer db.Close()

    vars := mux.Vars(r)
    mobilephone := vars["mobilephone"]
    output := vars["output"]

    var(
        smsblast1 SMSBlast
    )


    countSequenceId := db.Debug().Raw("SELECT COUNT (*) FROM SMSBlast2").Scan(&smsblast1)
    fmt.Println(countSequenceId)


    msg, err :=  json.Marshal(countSequenceId)
    if err != nil{
        fmt.Println(err.Error())
    }



    sequenceid1,_ := strconv.Atoi(string(msg))
    fmt.Println("SequenceID : " , sequenceid1)

    smsblasts := SMSBlast{SequenceID: sequenceid1,MobilePhone: mobilephone,Output:output, DtmUpd: time.Now()}
    prindata := db.Create(&smsblasts)
    fmt.Println(prindata)

func handleRequests(){
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/smsblaststest",allSMSBlasts).Methods("POST")
    myRouter.HandleFunc("/smsblaststestInsert/{mobilephone}/{output}", insertSMSBlast).Methods("POST")
    log.Fatal(http.ListenAndServe(":8080",myRouter))

}

func main(){
    fmt.Println("SMSBLASTS ORM")
    handleRequests()
}
  • 写回答

1条回答 默认 最新

  • dongtu7567 2019-02-16 06:44
    关注

    I'm not sure why you're using the Raw method for this, but I'd like to point out there's a Count method to achieve what you want: http://gorm.io/docs/query.html#Count

    db.Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Find(&users).Count(&count)
    //// SELECT * from USERS WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (users)
    //// SELECT count(*) FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (count)
    
    db.Model(&User{}).Where("name = ?", "jinzhu").Count(&count)
    //// SELECT count(*) FROM users WHERE name = 'jinzhu'; (count)
    

    I put together a very simple example from the docs:

    package main
    
    import (
        "fmt"
    
        "github.com/jinzhu/gorm"
        _ "github.com/jinzhu/gorm/dialects/sqlite"
    )
    
    type Porg struct {
        gorm.Model
        Name string
    }
    
    func main() {
        db, err := gorm.Open("sqlite3", "test.db")
        if err != nil {
            panic("failed to connect database")
        }
        defer db.Close()
    
        // Migrate the schema
        db.AutoMigrate(&Porg{})
    
        // Create
        for i := 1; i <= 100; i++ {
            db.Create(&Porg{Name: "John"})
        }
    
        // Read
        var porgs []Porg
        var count int
        db.Model(&porgs).Count(&count)
    
        fmt.Println(count)
    }
    

    Output: 100

    Using the Model method you can Specify a model to query, this won't query the DB directly. Using db.Find(&porgs).Count(&count) will actually send 2 SQL queries to the db.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看