Golang SQL查询变量替代 [英] Golang SQL query variable substituion

查看:262
本文介绍了Golang SQL查询变量替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要变量替换的sql查询,以便更好地使用 go-kit 服务。

I have sql query that needs variable substitution for better consumption of my go-kit service.

我有 dep & org 作为我的休息服务的一部分的用户输入,例如: dep ='abc' org ='def'

I have dep & org as user inputs which are part of my rest service, for instance: dep = 'abc' and org = 'def'.

我尝试了以下几种操作:

I've tried few things like:

rows, err := db.Query(
    "select name from table where department='&dep' and organisation='&org'",
)

并且:

rows, err := db.Query(
    "select name from table where department=? and organisation=?", dep , org,
)

导致错误: sql:语句期望输入0;得到2

只有硬编码的值有效,替换失败。

Only hard-coded values work and substitution fails .

I尚未从Oracle博客那里找到很多有关此方面的帮助,并且想知道是否有任何方法可以解决此问题。

I haven't found much help from oracle blogs regarding this and wondering if there is any way to approach this.

推荐答案

参数占位符语法(参考: http://go-database-sql.org/prepared.html

Parameter Placeholder Syntax (reference: http://go-database-sql.org/prepared.html )


在准备好的语句中占位符参数的语法是
特定于数据库的。例如,比较MySQL,PostgreSQL和
Oracle:

The syntax for placeholder parameters in prepared statements is database-specific. For example, comparing MySQL, PostgreSQL, and Oracle:



MySQL               PostgreSQL            Oracle
=====               ==========            ====== 
WHERE col = ?       WHERE col = $1        WHERE col = :col 
VALUES(?, ?, ?)     VALUES($1, $2, $3)    VALUES(:val1, :val2, :val3)

对于oracle,您需要使用:dep,:org作为占位符。

For oracle you need to use :dep, :org as placeholders.

这篇关于Golang SQL查询变量替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆