2

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.