Home >Backend Development >Golang >How to Query MySQL with a Slice of IDs Using SQLx?

How to Query MySQL with a Slice of IDs Using SQLx?

DDD
DDDOriginal
2024-12-05 12:34:10903browse

How to Query MySQL with a Slice of IDs Using SQLx?

Using SQLx to Query MySQL for Values in a Slice

When querying a MySQL table for values contained in a slice, users may encounter an error similar to:

sql: converting Exec argument #0's type: unsupported type []int, a slice

This issue arises because SQLx doesn't inherently support querying with a slice as an argument. However, it provides a solution through its In() function.

Solution with In()

To resolve this error, the following steps can be taken:

  1. Prepare the query using In() to include the slice as an argument:

    query, args, err := sqlx.In("SELECT * FROM quote WHERE qid IN (?)", qids)
    if err != nil {
     log.Fatal(err)
    }
  2. Rebind the query to make it compatible with the database backend:

    query = database.SQL.Rebind(query)
  3. Execute the query using Select():

    err = database.SQL.Select(&quotes, query, args...)

Combination in One Line

The entire process can be simplified into a single line:

err = database.SQL.Select(&quotes, database.SQL.Rebind(query), args...)

Resources

For additional examples and documentation, please refer to the official SQLx website: http://jmoiron.github.io/sqlx/

The above is the detailed content of How to Query MySQL with a Slice of IDs Using SQLx?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn