Using Python to access SQL with a variable column name

依然范特西╮ 提交于 2019-12-23 06:24:22

问题


I'm quite new to Python (and coding in general) and trying a small project that links my code to a MySQL database using pymysql. In general everything has gone smoothly but i'm having difficulty with the following function to find the min of a variable column.

def findmin(column):
    cur = db.cursor()
    sql = "SELECT MIN(%s) FROM table"
    cur.execute(sql,column)
    mintup = cur.fetchone()

if everything went smoothly this would return me a tuple with the min e.g. (1,)

however the issue is if i run the function:

findmin(column_name)

i have to put column name in "" (i.e. "column_name") else Python sees it as an unknown variable. But if i put the quotation marks round column_name then SQL sees

SELECT MIN("column_name") FROM table

which just returns the column header not the value. Any ideas how i can get round this?

Thanks for your help!


回答1:


The issue is likely the use of %s for the column name. That means the SQL Driver will try to escape that variable when interpolating it, including quoting, which is not what you want for things like column names, table names, etc.

When using a value in SELECT, WHERE, etc. then you do want to use %s to prevent SQL injections and enable quoting, among other things.

Here, you just want to interpolate using pure python. That also means no bindings tuple passed to the execute method.

def findmin(column):
    cur = db.cursor()
    sql = "SELECT MIN({0}) FROM table".format(column)
    cur.execute(sql)
    mintup = cur.fetchone()

SQL fiddle showing the SQL working:

http://sqlfiddle.com/#!2/e70a41/1



来源:https://stackoverflow.com/questions/24748898/using-python-to-access-sql-with-a-variable-column-name

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