Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...