1

I am trying to create a MySql user from a Golang program but I am unable to find the correct formatting of the SQL string:

    _, err := db.Query("CREATE USER ?@`%` IDENTIFIED BY ?",username)

I have tried many variations: enclosing the ? in backticks, single quotes, parenthesis, but nothing works.

I either get sql: expected 0 arguments, got 1 (or 2 if I add one or two parameters), or I get

Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?@`%` IDENTIFIED BY ?' at line 1

I have found similar questions but none is using the CREATE USER, and none of the solutions found there worked for me. Thanks

bennythejudge
  • 6,353
  • 2
  • 13
  • 11
  • 1
    See https://stackoverflow.com/questions/11368966/syntax-error-from-create-user-with-variables-giving-username-and-password and https://stackoverflow.com/a/11951620/965900 – mkopriva Jun 07 '19 at 12:38
  • Thank you @mkopriva but neither of those is a Go problem. I was having a problem with using the placeholders in Go. But thanks anyway. – bennythejudge Jun 07 '19 at 22:04
  • If I'm not mistaken both of them point to a bug in **mysql** which causes the placeholders not work for the `CREATE USER` command. Go or not go, the problem is in mysql, at least that's how I understood it. And if you think Go does the placeholder replacement and not mysql I would think twice. – mkopriva Jun 07 '19 at 22:08

1 Answers1

0

I have found a workaround:

    password := "aaargh!"
    s := "CREATE USER '" + username + "'@`%` IDENTIFIED BY '" + password + "'"

This is working in my test.

bennythejudge
  • 6,353
  • 2
  • 13
  • 11
  • What is wrong @Volker? Could you pls explain? It does work in my program. – bennythejudge Jun 07 '19 at 22:01
  • 1
    @Benedetto the problem with building sql statements with string concatenation is that you're simply exposing yourself to sql injection. – mkopriva Jun 07 '19 at 22:14
  • 1
    @mkopriva thanks a lot. I am aware of this issue. I am only building an internal automation that will not be exposed externally and will not receive uncontrolled input. Besides I am a beginner with Go so I am just doing my best, but I would not use unsanitized SQL if this was coming from an external source such as a form or similar. – bennythejudge Jun 08 '19 at 19:07