dousuize3082 2018-09-14 23:45
浏览 178
已采纳

Golang SQL查询变量替换

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

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'",
)

And:

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

That led to error: sql: statement expects 0 inputs; got 2

Only hard-coded values work and substitution fails .

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

  • 写回答

2条回答 默认 最新

  • donglinxin8765 2018-09-15 05:15
    关注

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

    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)
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dtftao7249656 2018-09-15 09:32
    关注

    As @dakait stated, on your prepare statement you should use : placeholders.

    So, for completeness, you would get it working with something like:

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
    )
    
    // Output is an example struct
    type Output struct {
        Name string
    }
    
    const (
        dep = "abc"
        org = "def"
    )
    
    func main() {
    
        query := "SELECT name from table WHERE department= :1 and organisation = :2"
    
        q, err := db.Prepare(query)
        if err != nil {
            log.Fatal(err)
        }
    
        defer q.Close()
    
        var out Output
    
        if err := q.QueryRow(dep, org).Scan(&out.Name); err != nil {
            log.Fatal(err)
        }
    
        fmt.Println(out.Name)
    
    }
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Google Chrome 所有页面崩溃,三种解决方案都没有解决,我崩溃了
  • ¥18 如何用c++编写数学规律题
  • ¥20 使用uni-app发起网络请求,获取重定向302返回的cookie
  • ¥20 手机外部浏览器拉起微信小程序支付 (相关搜索:微信小程序)
  • ¥20 怎样通过一个网址找到其他同样模版的网址
  • ¥30 XIAO esp32c3 读取FDC2214的数据
  • ¥15 在工控机(Ubuntu系统)上外接USB蓝牙硬件进行蓝牙通信
  • ¥15 关于PROCEDURE和FUNCTION的问题
  • ¥100 webapi的部署(标签-服务器)
  • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)