Is there any safe way to parameterize database names in MySQL queries?

一曲冷凌霜 提交于 2019-12-19 10:10:52

问题


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?


回答1:


A database name (nor column or table names) are not data values, and thus are not an appropriate use of placeholders. wanting to do this is usually a bad sign; only the DBA should be able to issue a create database, since doing so requires some considerable privileges. Most applications require the DBA to issue the create database, and then take the created database as a parameter to be used in the arguments to dbapi.Connection.

If you are sure you need this, you trust the source of the input, and you have checked the input for invalid characters, you would just do the substitution in python, something like:

def createDB(dbConn, dbName):
    c = dbConn.cursor()
    query = """CREATE DATABASE %s;""" % dbName
    c.execute(query)



回答2:


After some digging it turns out that phpmyadmin uses backticks to quote database, table, and column names. They simply do:

$sql_query = 'CREATE DATABASE ' . PMA_backquote($new_db);  

Which would give in the error case above something like

CREATE DATABASE `test_db; DROP some_other_db`;

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.



来源:https://stackoverflow.com/questions/6656636/is-there-any-safe-way-to-parameterize-database-names-in-mysql-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!