2

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?

1 Answer 1

1

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

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.