【问题标题】:Go Lang, Postgres: cannot get oid after ScanGo Lang,Postgres:扫描后无法获取 oid
【发布时间】:2018-11-13 01:28:16
【问题描述】:

如果表accounts,我有2列:

oidbalance

通过下一个代码,我尝试提取oid 然后balance

// variable `id` comes from an another part

sqlstr := `SELECT * ` +
    `FROM accounts ` +
    `WHERE oid=` + id + `;`

q, err := db.Query(sqlstr)

if err != nil {
    fmt.Println("Error: GetAccount \n", err)
    return Account{}, err
}
defer q.Close()


var _id string
var bal float64

q.Next()
q.Scan(&_id)
fmt.Println("_id ", _id)


q.Next()
q.Scan(&bal)
fmt.Println("bal ", bal)

在第一个q.Next() 之后,我希望提取oid,在第二个之后提取balance

但每次在第一个q.Next() 之后和第二个之后我只得到balance

我尝试将sqlstr更改为下一个:

sqlstr := `SELECT oid, balance ` +
    `FROM accounts ` +
    `WHERE oid=` + id + `;`

但我仍然无法提取oid。

【问题讨论】:

    标签: postgresql go psql


    【解决方案1】:

    试试这个q.Scan(&_id, &bal)func (*Row) Scan有这个签名:

    func (r *Row) Scan(dest ...interface{}) error
    

    它期望指针指向它将存储查询数据的值。

    如果您只查询单行,则有func (*DB) QueryRow()。然后您的代码将简化为

    row := db.QueryRow(sqlstr)
    err := row.Scan(&_id, &bal)
    // err will be sql.ErrNoRows if no rows have been selected
    

    【讨论】:

    • 上面写着:sql: expected 1 destination arguments in Scan, not 2
    • 您使用的是什么确切的 PG 库?是这个吗:github.com/lib/pq?你是如何打开你的数据库连接的?
    • 您是否像这样打开数据库连接:db, err := sql.Open("postgres", connStr)?
    • 我使用github.com/lib/pq作为数据库驱动程序,但连接数据库我使用github.com/xo/dburl
    • 所以解决方案是在sql查询字符串中使用oid, balance而不是*,使用db.QueryRow()而不是db.Query(),并使用@987654335 @根据sql查询字符串中的oid, balance
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多