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

3
  • 1
    See stackoverflow.com/questions/11368966/… and stackoverflow.com/a/11951620/965900 Commented Jun 7, 2019 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. Commented Jun 7, 2019 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. Commented Jun 7, 2019 at 22:08

1 Answer 1

0

I have found a workaround:

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

This is working in my test.

Sign up to request clarification or add additional context in comments.

4 Comments

What is wrong @Volker? Could you pls explain? It does work in my program.
@Benedetto the problem with building sql statements with string concatenation is that you're simply exposing yourself to sql injection.
@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.
Please note that you should sanitize username valUsername = regexp.MustCompile("[^a-zA-Z0-9_]+").ReplaceAllString(username, "") and escape single quote: valPassword = strings.ReplaceAll(password, "'", "''")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.