Python-MySQL : removing single quotes around variable values in query while running db.execute(str, vars)

时光毁灭记忆、已成空白 提交于 2020-01-07 06:54:46

问题


I am running this code

    def details(self, dbsettings, payload):
        res = None
        with UseDatabase(dbsettings) as db:
            sql = "select * from %(tablename)s where userid = %(userid)s"
            result = db.run_query_vals(sql, payload)
            res = result.fetchall()
        return res

but get an error

SQLError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''statuser' where userid = '14'' at line 1

The arguments being passed are :

sql = "select * from %(tablename)s where userid = %(userid)s"
payload = {'tablename' : 'statuser', 'userid' : 14}

As far as I understand, the query being passed to MySQL is along the lines of

select * from 'statuser' where userid = '14'

which is where I get the error; the tablename isnt supposed to be enclosed in quotes. How do I have the name included without the quotes/make them backquotes?

(I don't want to hard-code the table name - this is a variable and is initialised according to different parameters during class creation). Any help here?


回答1:


You can use the .format() from string in python:

def details(self, dbsettings, payload):
    res = None
    with UseDatabase(dbsettings) as db:
        sql = "select * from {tablename} where userid = {userid}"
        sql = sql.format(**payload)
        # result = db.run_query_vals(sql, payload) # Method to run query
        res = result.fetchall()
    return res



回答2:


I encountered the same problem in pymysql and have figured out a solution:

rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string.

don't know whether it will help in your case, just sharing a possible way

similiar question: How to remove extra quotes in pymysql

Here's my code:

from pymysql.connections import Connection, converters


class MyConnect(Connection):
    def escape(self, obj, mapping=None):
        """Escape whatever value you pass to it.

        Non-standard, for internal use; do not use this in your applications.
        """
        if isinstance(obj, str):
            return self.escape_string(obj)  # by default, it is :return "'" + self.escape_string(obj) + "'"
        if isinstance(obj, (bytes, bytearray)):
            ret = self._quote_bytes(obj)
            if self._binary_prefix:
                ret = "_binary" + ret
            return ret
        return converters.escape_item(obj, self.charset, mapping=mapping)


config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()


来源:https://stackoverflow.com/questions/44597536/python-mysql-removing-single-quotes-around-variable-values-in-query-while-runn

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