Skip to content

in (?) cannot work and no error  #107

Closed
@meilihao

Description

@meilihao
var sets []string =[]string{"0001","0004"}
rows, err := db.Query(`SELECT set_id,set_name FROM sets where  set_id in (?)`, strings.Join(sets, ","))

[can't work]

in mysql workbench:
SELECT set_id,set_name FROM sets where set_id in ("0001","0004") [can work]

Activity

alxzh

alxzh commented on Jul 10, 2013

@alxzh

This is OK because '?' In go code adds quotes around whole string which
different from you mysql console example. This isn't go specific
peculiarity. So I'd propose to rework your code.
On Jul 10, 2013 12:38 PM, "chenhao" notifications@github.com wrote:

go:
var sets []string =[]string{"0001","0004"}
rows, err := db.Query(SELECT set_id,set_name FROM sets where set_id in (?),
strings.Join(sets, ",")) [can't work]

in mysql workbench:
SELECT set_id,set_name FROM sets where set_id in ("0001","0004") [can work]


Reply to this email directly or view it on GitHubhttps://github.com//issues/107
.

arnehormann

arnehormann commented on Jul 10, 2013

@arnehormann
Member

@meilihao @alexvizor Each ? represents exactly one value. It's impossible to bind multiple values to it this way.
Try this instead, which is equivalent to the mysql workbench query:

sets := []string{"0001","0004"}
rows, err := db.Query(
    "SELECT set_id,set_name FROM sets where set_id in ('" +
    strings.Join(sets, "','") + "'"
)
arnehormann

arnehormann commented on Jul 10, 2013

@arnehormann
Member

@meilihao this still leaves one open issue: what is "no error" in the title?
None at all or an error you didn't understand? Did you check err?

julienschmidt

julienschmidt commented on Jul 10, 2013

@julienschmidt
Member

But please be aware that @arnehormann's example is not injection safe. I'd recommend to set each value separately (one ? for each value) if possible.
You should be absolutely sure that the string slice only contains numeric values. Alternatively you could simply save them in a int slice, but this would make the query building a bit more complex.

arnehormann

arnehormann commented on Jul 10, 2013

@arnehormann
Member

Yes, my example is intended for a previously unknown number of strings provided by the developer and independent of user input. If the number of arguments is known, use the right amount of ?s. Don't open your code to SQL-injections. I probably should have added that in my comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @julienschmidt@arnehormann@alxzh@meilihao

        Issue actions

          in (?) cannot work and no error · Issue #107 · go-sql-driver/mysql