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
Release: 2024-12-05 12:34:10
Original
900 people have browsed it

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
Copy after login

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)
    }
    Copy after login
  2. Rebind the query to make it compatible with the database backend:

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

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

Combination in One Line

The entire process can be simplified into a single line:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template