我在实现2个参数时遇到问题:http://localhost:8080/SMSBlast/SequenceID?SequenceID=2&MobilePhone=85261415223
如何使用两列SequenceID
和MobilePhone
进行查询以获得SequenceID=2&MobilePhone=85261415223
,我尝试了很多方法,但仍然无法使用
package main
import (
"database/sql"
"fmt"
_ "github.com/denisenkom/go-mssqldb"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func main() {
db, err := sql.Open("sqlserver","sqlserver://sa:@localhost:1433?database=CONFINS&connection+timeout=30")
if err != nil{
fmt.Print(err.Error())
}
err = db.Ping()
if err != nil {
fmt.Print(err.Error())
}
defer db.Close()
type SMSBlast struct {
SequenceID int
MobilePhone string
Output string
WillBeSentDate *time.Time
SentDate *time.Time
Status *string
DtmUpd *time.Time
}
router := gin.Default()
//Get a SMSBlast detail
router.POST("/SMSBlast/:SequenceID", func(context *gin.Context) {
var(
smsblast SMSBlast
result gin.H
)
SequenceID := context.Param("SequenceID")
MobilePhone := context.Param("MobilePhone")
err := db.QueryRow("SELECT SequenceID,MobilePhone,Output,WillBeSentDate, SentDate, Status, DtmUpd FROM SMSBlast2 Where SequenceID = ? AND MobilePhone = ? "+SequenceID , MobilePhone).Scan(&smsblast.SequenceID, &smsblast.MobilePhone, &smsblast.Output, &smsblast.WillBeSentDate, &smsblast.SentDate, &smsblast.Status, &smsblast.DtmUpd)
//fmt.Println(row)
fmt.Println(err)
//err = row.Scan(&smsblast.SequenceID, &smsblast.MobilePhone, &smsblast.Output, &smsblast.WillBeSentDate, &smsblast.SentDate, &smsblast.Status, &smsblast.DtmUpd)
if err != nil{
//if no results send null
result = gin.H{
"result": nil,
"count": 0,
}
}else{
result = gin.H{
"result" : smsblast,
"count" : 1,
}
}
context.JSON(http.StatusOK, result)
})
答案 0 :(得分:0)
您的语法不正确。试试这个:
err := db.QueryRow("SELECT SequenceID,MobilePhone,Output,WillBeSentDate, SentDate, Status, DtmUpd FROM SMSBlast2 Where SequenceID = $1 AND MobilePhone = $2", SequenceID, MobilePhone).Scan(&smsblast.SequenceID, &smsblast.MobilePhone, &smsblast.Output, &smsblast.WillBeSentDate, &smsblast.SentDate, &smsblast.Status, &smsblast.DtmUpd)
编辑:
该查询包含枚举为$1
,$2
等的占位符。这些占位符用于包含作为参数的变量。在您的评论中,您将$1
替换为$3
。那不是它的工作原理。将其保留为$1
,将值存储在SequenceID
变量中,然后将该变量传递给QueryRow
。
这是一个简化的示例,以说明:
SequenceID := 3
err := db.QueryRow("SELECT * FROM SMSBlast2 WHERE SequenceID = $1", SequenceID).Scan(...)
现在有两个参数:
SequenceID := 3
MobilePhone := "85261415223"
err := db.QueryRow("SELECT * FROM SMSBlast2 WHERE SequenceID = $1 AND MobilePhone = $2", SequenceID, MobilePhone).Scan(...)
答案 1 :(得分:0)
请尝试使用Query()
,例如here:
SequenceID := context.Query("SequenceID")
MobilePhone := context.Query("MobilePhone")