Reputation: 88
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?
Upvotes: 0
Views: 69
Reputation: 46
You can't. Prepared statement placeholders bind parameter values only, not identifiers.
Upvotes: 3