How to execute an IN lookup in SQL using Golang?

前端 未结 9 841
余生分开走
余生分开走 2020-12-01 02:12

What does Go want for the second param in this SQL query. I am trying to use the IN lookup in postgres.

stmt, err := db.Prepare(\"SELECT * FRO         


        
相关标签:
9条回答
  • 2020-12-01 02:30

    if you use sqlx, you can follow this way: https://github.com/jmoiron/sqlx/issues/346

    arr := []string{"this", "that"}
    query, args, err := sqlx.In("SELECT * FROM awesome_table WHERE id=10 AND other_field IN (?)", arr)
     
    query = db.Rebind(query) // sqlx.In returns queries with the `?` bindvar, rebind it here for matching the database in used (e.g. postgre, oracle etc, can skip it if you use mysql)
    rows, err := db.Query(query, args...)
    
    0 讨论(0)
  • 2020-12-01 02:31
    //I tried a different way. A simpler and easier way, maybe not too efficient.
    stringedIDs := fmt.Sprintf("%v", ids)
    stringedIDs = stringedIDs[1 : len(stringedIDs)-1]
    stringedIDs = strings.ReplaceAll(stringedIDs, " ", ",")
    query := "SELECT * FROM users WHERE id IN ("  + stringedIDs + ")"
    //Then follow your standard database/sql Query
    rows, err := db.Query(query)
    //error checking
    if err != nil {
        // Handle errors
    } else {
        // Process rows
    }
    
    0 讨论(0)
  • 2020-12-01 02:34

    With PostgreSQL, at least, you have the option of passing the entire array as a string, using a single placeholder:

    db.Query("select 1 = any($1::integer[])", "{1,2,3}")
    

    That way, you can use a single query string, and all the string concatenation is confined to the parameter. And if the parameter is malformed, you don't get an SQL injection; you just get something like: ERROR: invalid input syntax for integer: "xyz"

    https://groups.google.com/d/msg/golang-nuts/vHbg09g7s2I/RKU7XsO25SIJ

    0 讨论(0)
提交回复
热议问题