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?