PyMySQL variables in queries

老子叫甜甜 提交于 2019-12-01 19:47:50

问题


I would like to have a connection between my python code and a SQL database. I have read several ways to do it , but I am failing to get the results.

conn = pymysql.connect(user=X,passwd=X,host=X,port=X,database=X, charset='utf8', autocommit=True)
curs = conn.cursor()

try:
    curs.execute('SELECT id,sing_name,bir_yr FROM singers_list WHERE bir_yr = ? ',year)
    data = curs.fetchall()       
    for i in data:
        yield " Data: " + str(i) + "<br/>"
except:
    yield " Failed to get data from base<br/>"

Where year is an int python variable. I am getting the proper results with:

curs.execute('SELECT id,sing_name,bir_yr FROM singers_list)

Which means I am connecting successfully to the database . How can I include variables in queries ? (not only integers , but strings too or any type)


回答1:


You have to pass the parameters inside an iterable - commonly a tuple:

query = 'SELECT id,sing_name,bir_yr FROM singers_list WHERE bir_yr = %s'
curs.execute(query, (year, ))

Note that I've also replaced the ? placeholder with %s.

Also note that the MySQL driver would automatically handle the type conversion between Python and MySQL, would put quotes if necessary and escape the parameters to keep you safe from SQL injection attacks.



来源:https://stackoverflow.com/questions/37094159/pymysql-variables-in-queries

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