I’m writing a little python script to help me automate the creation of mysql databases and associated accounts for my personal projects. Part of this script is a function that takes the database name as a string, then goes to create the database.
def createDB(dbConn, dbName):
import MySQLdb
c = dbConn.cursor()
query = """CREATE DATABASE %s;""";
c.execute(query, (dbName,))
This doesn’t work because MySQL’s CREATE DATABASE asks for the unquoted name of the database, as in
CREATE DATAbASE test_db
but my code that attempts to safely insert the user provided db name into the query creates:
CREATE DATABASE 'test_db'
And you get “you have a problem in your MySQL syntax near test”.
Even though this is for personal use, I really don’t want to just directly insert a user provided string into a query of any kind. Its against my religion. Is there a safe way to insert a user-provided database name into a mySQL query in python (or any language) that will make sure that user input such as test_db; DROP some_other_db; will get rejected or escaped correctly?
After some digging it turns out that phpmyadmin uses backticks to quote database, table, and column names. They simply do:
Which would give in the error case above something like
Of course any backticks in the input string need to be escaped, which according to phpmyadmin’s code is done by replacing all single back ticks with double back ticks. I can’t find any where that confirms that this is correct.
I also noticed online though that backticks are not standard SQL.