Create MySQL Database in Python using the %s opera

2019-07-31 18:57发布

问题:

Trying to create a database where the name is given through the %s operator.

import mysql.connector, MySQLdb
db_name='SomeString'

#create connection to mysql
mydb=mysql.connector.connect(host="localhost",user="root")

#init cursor
mycursor=mydb.cursor()

#create database
mycursor.execute("CREATE DATABASE (%s)", (db_name))

This is the error msg:

mysql.connector.errors.ProgrammingError: 1064 (42000): 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)' at line 1

回答1:

I think you are intending the value of db_name to be inserted instead of the %s, like a placeholder in C. This doesn't work as you have found out. Instead, you could do something like:

create_statement = "CREATE DATABASE {:s}".format(db_name)
mycursor.execute(create_statement)

Doing it this way will allow you to use the technique in more complex situations where there is more SQL after the value you are trying to substitute.