使用 gorm 和 GORM LOG sql:预期 0 个参数,得到 1 个参数。

问题描述 投票:0回答:1

GORM LOG sql: 预期0个参数,得到1个参数

我的代码是

func GetPipelineConfigKey(riskConfigKey string) string{
    var PipelineConfigKey string
    sql := fmt.Sprintf("SELECT context_name FROM hawk_context_name WHERE id = (SELECT service_line_id FROM risk_predict_config_key WHERE config_key = '%s');", riskConfigKey)
    contextDb.Exec(sql, &PipelineConfigKey)
    return PipelineConfigKey
}

enter image description here

gorm
1个回答
0
投票

Exec 具有以下签名

func (s *DB) Exec(sql string, values ...interface{}) *DB {

values在这里是一个varargs参数,对于你传给Exec的每一个变量,都应该有一个 ? 在你的 sql 查询中。你传递了1个参数,但查询不需要任何参数(无 ?). 这就是为什么你得到以下错误。

sql: expected 0 arguments, got 1

也许你想把结果保存在 PipelineConfigKey. 用这种方式来处理

创建一个结果结构

type Result struct {
    Name string
}

和扫描结果

db.Raw(sql).Scan(&result)

完整代码

type Result struct {
        Name string
}

func GetPipelineConfigKey(riskConfigKey string) string{
    sql := fmt.Sprintf("SELECT context_name FROM hawk_context_name WHERE id = (SELECT service_line_id FROM risk_predict_config_key WHERE config_key = '%s');", riskConfigKey)
    db.Raw(sql).Scan(&result)
    return result.Name
}
© www.soinside.com 2019 - 2024. All rights reserved.