Python-MySQL:在运行db.execute(str,vars)时,删除查询中变量值的单引号 [英] Python-MySQL : removing single quotes around variable values in query while running db.execute(str, vars)

查看:265
本文介绍了Python-MySQL:在运行db.execute(str,vars)时,删除查询中变量值的单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行这段代码

    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

但出现错误

SQLError:1064(42000):您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册以获取正确的语法,以便在"statuser"(第1行的userid ='14')附近使用

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

要传递的参数是:

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

据我了解,传递给MySQL的查询大致是

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

从'statuser'中选择*,其中userid ='14'

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?

推荐答案

您可以在python中的字符串中使用.format():

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

这篇关于Python-MySQL:在运行db.execute(str,vars)时,删除查询中变量值的单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆