登录
首页 >  Golang >  Go问答

如何在 mysql 查询中使用“fmt”

来源:stackoverflow

时间:2024-03-17 23:55:51 407浏览 收藏

在 MySQL 查询中,无法使用“?”来绑定列名,只能绑定值。要构建动态查询,可以使用 `fmt` 构建查询字符串。例如,可以将查询字符串存储在变量中,然后使用 `?` 绑定值: ```go select_all_userid := fmt.Sprintf("select user_id from notification_settings where is_%s = 1 and is_%s_oclock = 1 and frequency = ? and is_holiday = ?", isLine, isHourClock) ```

问题内容

我使用 fmt 在 my_table 中创建两个字段。

const   (
    SELECT_ALL_USERID = "select user_id from notification_settings where ? = 1 and ? = 1 and frequency = ? and is_holiday = ?"
)

func (user_station) GetAllUserId(db *gorp.DbMap,isLine string ,isHourClock int ,frequency , isHoliday string) ([]models.UserID,error) {
    var listUserId []models.UserID
    var is_line = fmt.Sprintf("is_%s",isLine)
    var is_hour_oclock = fmt.Sprintf("is_%d_oclock",isHourClock)
    _,err := db.Select(&listUserId,SELECT_ALL_USERID,is_line,is_hour_oclock,frequency,isHoliday)
    return listUserId,err
}

所以,我在 where 子句中尝试了 ? 但失败了。我缺少什么?


解决方案


您不能使用 ? 绑定列名,只能绑定值。相反,使用 fmt 构建查询字符串:

select_all_userid:=fmt.Sprintf("select user_id from notification_settings where is_%s = 1 and is_%s_oclock = 1 and frequency = ? and is_holiday = ?",isLine,isHourClock)

到这里,我们也就讲完了《如何在 mysql 查询中使用“fmt”》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>