0

I am trying to create new MySQL database:

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/go-sql-driver/mysql"
)

func createDBIfNotExists() {
    const (
        DB_NAME = "new_db"
        DB_USER = "root"
        DB_PASS = "777"
        DB_HOST = "localhost"
        DB_PORT = "3306"
    )

    var dbUrl = fmt.Sprintf("%s:%s@tcp(%s:%s)/", DB_USER, DB_PASS, DB_HOST, DB_PORT)

    db, err := sql.Open("mysql", dbUrl)
    defer db.Close()
    handleError(err)

    prepared, err := db.Prepare("CREATE DATABASE IF NOT EXISTS ?")
    handleError(err)

    _, err = prepared.Exec(DB_NAME)
    handleError(err)
}

func main() {
    createDBIfNotExists()
}

func handleError(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

But this code returns error:

2017/10/13 12:46:16 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 '?' at line 1

If I changed this code and concatenate DB name to query:

prepared, err := db.Prepare("CREATE DATABASE IF NOT EXISTS " + DB_NAME)
handleError(err)
_, err = prepared.Exec()

it will be OK, but i don't wont to have potential SQL injection.

How i can prepare and execute creation of DB?

1 Answer 1

3

You can't. Prepared statement placeholders bind parameter values only, not identifiers.

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

2 Comments

Thank you for answer. It looks like concatenation the only way to solve this problem, but in my case DB_NAME is received from environment variable and i must write validation code if i want concatenate it
@volodymyrkoval: Correct. You must provide your own validation in this case.

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.