big-chungus
big-chungus

Reputation: 35

sql.DB.Query "expected 0 arguments" when using "?" placeholder

I am interacting with a MySQL database in golang using database/sql with the github.com/go-sql-driver/mysql driver

I associate tags to articles with a table article_to_tag which associates an article ID with a tag ID, and find articles with certain tags using a Toxi solution found toward the bottom of this article

This snippet is supposed to query my database for all articles associated with all tags in the array itags

    s := "SELECT a.* " +
        "FROM article_to_tag at, articles a, tags t " +
        "WHERE t.ID = at.TagID " +
        "AND a.ID = at.ArticleID " +
        "AND (t.Name IN ('?'" + strings.Repeat(",'?'", len(itags)-1) + ")) " +
        "GROUP BY a.ID " +
        "HAVING COUNT(a.ID)=" + strconv.Itoa(len(itags)) + ";"
    fmt.Println(s)
    rows, err := db.Query(s, itags...)

This builds the following string when querying for 2 tags, but querying with that string returns an error: sql: expected 0 arguments, got 2

SELECT a.*
FROM article_to_tag at, articles a, tags t
WHERE t.ID = at.TagID
AND a.ID = at.ArticleID
AND (t.Name IN ('?','?'))
GROUP BY a.ID HAVING COUNT(a.ID)=2;

Why is the query ignoring the ? placeholder, and how else should I go about building the query safely?

Upvotes: 2

Views: 378

Answers (1)

MvG
MvG

Reputation: 61047

Omit the single quotes. When you use a placeholder, place it unquoted. With the quotes it's just a string.

Upvotes: 1

Related Questions