1

I have 2 columns if table accounts:

oid and balance

By the next code I try to extract oid then 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)

After the first q.Next() I expected to extract oid and after the second to extract balance.

But every time after the first q.Next() and after the second I only get balance.

I tried to change sqlstr to the next:

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

But I still cannot extract oid.

1 Answer 1

1

Try this q.Scan(&_id, &bal), func (*Row) Scan has this signature:

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

It expects the the pointers to the values where it will store the queried data.

If you are only querying for a single row, there is func (*DB) QueryRow(). Then your code will simplify to

row := db.QueryRow(sqlstr)
err := row.Scan(&_id, &bal)
// err will be sql.ErrNoRows if no rows have been selected
Sign up to request clarification or add additional context in comments.

8 Comments

It says: sql: expected 1 destination arguments in Scan, not 2
What exact PG library are you using? Is it this one: github.com/lib/pq? How are you opening your database connection?
Are you opening your DB connection like this: db, err := sql.Open("postgres", connStr)?
I use github.com/lib/pq as DB driver, but to connect DB I use github.com/xo/dburl
So the solution is to use oid, balance instead of * in sql query string, to use db.QueryRow() instead of db.Query(), and to use row.Scan(&_id, &bal) according to oid, balance in sql query string.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.