twharmon
twharmon

Reputation: 4272

Golang database/sql.DB.QueryRow with multiple args

I want to execute a query something like this (using MySql):

select * from user where id = 5

Ex 1. This returns err = sql.ErrNoRows:

err := db.QueryRow("select * from user where ? = ?", f, v).Scan(&user.Id, etc...)

Ex 2. Since the above doesn't work, I am doing it this way, which works but doesn't feel right:

err := db.QueryRow("select * from user where "+f+" = ?", v).Scan(&user.Id, etc...)

What is wrong in Ex. 1? Is Ex 2. an acceptable way to do this?

EDIT

From the link in the comments I can do it a third way.

Ex 3:

q := fmt.Sprintf("select * from user where %s = ?", f)
err := db.QueryRow(q, v).Scan(&user.Id, etc...)

Upvotes: 0

Views: 3663

Answers (1)

Pavlo Strokov
Pavlo Strokov

Reputation: 2087

You need to provide column names directly in sql query. '?' sign is a placeholder for values you provide after sql string. Your Ex3. is correct, but it is not a good solution, because it is open for SQL-injection attacks.

If you need a lightweight solution you can create a map with known column names for each table like: userColumns := map[string]bool {"id": true, ...} and then just use next check:

if userColumns[f] {
    ...you able to use f in sql...
} else {
    ...provided value is not one of known columns, it is an error...
}

Upvotes: 1

Related Questions