简体   繁体   中英

Creating Mysql database with python - keep getting 1064 error (… right syntax to use near '%s' )

Here is the thing: I'm trying to make a new MySQL database by importing the name for the database and then creating it.

Here is the code:

import mysql.connector as mcon

# DB Connect
stdb = mcon.connect(
    host        = "localhost",
    user        = "root",
    password    = "pass",
    database    = "trffc_int_data")
cursor = stdb.cursor()

# Creating new DB
NewDB = input(" Enter the Database name : ")
sqlsynt = "CREATE DATABASE IF NOT EXISTS %s"
cursor.execute(sqlsynt,NewDB)                 
cursor.commit()
print ("New database created!") 

Looks right, but I keep getting error "1065 >> 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 '%s' <<"

It points the line: cursor.execute(sqlsynt,NewDB)

What could be the problem?

You can't bind object names (in this case - the database name) like that, only values. You'll have to resort to string formatting. Eg:

newDB = input(" Enter the Database name : ")
sqlsynt = f"CREATE DATABASE IF NOT EXISTS {newDB}"
cursor.execute(sqlsynt,NewDB)

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