Python MySQLdb placeholders syntax

你。 提交于 2019-12-01 07:31:24

问题


I'd like to use placeholders as seen in this example:

cursor.execute ("""
    UPDATE animal SET name = %s
    WHERE name = %s
    """, ("snake", "turtle"))

Except I'd like to have the query be its own variable as I need to insert a query into multiple databases, as in:

query = """UPDATE animal SET name = %s
           WHERE name = %s
           """, ("snake", "turtle"))
cursor.execute(query)
cursor2.execute(query)
cursor3.execute(query)

What would be the proper syntax for doing something like this?


回答1:


query = """UPDATE animal SET name = %s
           WHERE name = %s
           """
values = ("snake", "turtle")

cursor.execute(query, values)
cursor2.execute(query, values)

or if you want group them together...

arglist = [query, values]
cursor.execute(*arglist)
cursor2.execute(*arglist)

but it's probably more readable to do it the first way.



来源:https://stackoverflow.com/questions/2527941/python-mysqldb-placeholders-syntax

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