0

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...)
3
  • What's your question? Commented Jul 19, 2017 at 15:01
  • Related / possible duplicate of Golang ORDER BY issue with MySql. Commented Jul 19, 2017 at 15:31
  • 1
    Whether WHERE ? = ? works depends on your database driver, and what each ? represents. In the DBs I'm familiar with (Postgres, MySQL, and SQLite), you can use variable substitution only for values, not for column names. This means if f is your column name, your second try (and equivalent third) is not only "right", but the only option. Commented Jul 19, 2017 at 15:51

1 Answer 1

1

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...
}
Sign up to request clarification or add additional context in comments.

Comments

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.