简体   繁体   中英

Creating new MySQL database with Go using prepared query

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM