dqjgf0982 2016-05-25 23:00
浏览 74
已采纳

我对带有变量的Go sql查询不了解什么?

I'm brand new to Go, and I've started working on some postgres queries, and I'm having very little luck.

I have a package that's just going to have some database queries in it. Here's my code.

main.go

package main

import (
    "fmt"
)

func main() {

    fmt.Println("Querying data")
    myqueries.SelectAll("mytable")

}

myqueries.go

package myqueries

import (
    "database/sql"
    "fmt"
)

func SelectAll (table string) {
    db, err := sql.Open("postgres","user=postgres dbname=mydb sslmode=disable")

        if err != nil {
                 fmt.Println(err)
        }

        defer db.Close()

        rows, err := db.Query("SELECT * FROM $1", table)

        if err != nil {
                fmt.Println(err)
        } else {

                PrintRows(rows)
        }

}

func PrintRows(rows *sql.Rows) {
    for rows.Next() {
        var firstname string
        var lastname string

        err := rows.Scan(&firstname, &lastname)

        if err != nil {
            fmt.Println(err)
        }
        fmt.Println("first name | last name")

        fmt.Println("%v | %v
", firstname, lastname)

    }
}

The error I get is pq: syntax error at or near "$1"

which is from myqueries.go file in the db.Query.

I've tried several variations of this, but nothing has worked yet. Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • drc15469 2016-05-25 23:15
    关注

    It looks like you are using https://github.com/lib/pq based on the error message and it's docs say that

    pq uses the Postgres-native ordinal markers, as shown above

    I've never known a database engine that allows the parameterized values in anything other than values. I think you are going to have to resort to string concatenation. I don't have a Go compiler available to me right now, but try something like this. Because you are inserting the table name by concatination, you need it sanitized. pq.QuoteIdentifier should be able to help with that.

    func SelectAll (table string) {
        db, err := sql.Open("postgres","user=postgres dbname=mydb sslmode=disable")
    
            if err != nil {
                     fmt.Println(err)
            }
    
            defer db.Close()
    
            table = pq.QuoteIdentifier(table)
            rows, err := db.Query(fmt.Sprintf("SELECT * FROM %v", table))
    
            if err != nil {
                    fmt.Println(err)
            } else {
    
                    PrintRows(rows)
            }
    
    }
    

    EDIT: Thanks to hobbs to pointing out pq.QuoteIdentifier

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制