我现在尝试使用宁静的api,因为我故意这样计数countSequenceId:= db.Debug()。Table(“ SMSBlast2”)。Count( &smsblast1),结果为sql:列索引0上的扫描错误,名称“”:不支持的扫描,存储驱动程序。值类型int64到类型* main.SMSBlast
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 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()
}
答案 0 :(得分:0)
您似乎假设Gorm方法将为您返回结果。那不是它的工作原理。 Gorm返回错误或nil,然后将引用传递给要存储结果的变量。因此,要对某些内容使用Count(),您将编写类似
var count int
db.Model(&SMSBlast{}).Count(&count)
fmt.Printf("count: %d\n", count)
也就是说,如果您只是想确保每次都获得一个新的序列ID,为什么不使用自动增量?
type SMSBlast struct {
SequenceID int `gorm:"primary_key";column:"SequenceID";"AUTO_INCREMENT"`
...
}