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

孤者浪人 提交于 2019-12-01 11:18:10

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)

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.

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