pymysql:MySQL参数化查询

2024-10-01 11:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么我在尝试执行此查询时得到TypeError: not all arguments converted during string formatting?我需要能够将%{}%追加到传入的IP上,这样我就可以运行LIKEmysql查询。在

如果这不是使用%通配符参数化LIKE查询的正确方法,那么该怎么做?在

班级:

class IpCleaner(object):
    def __init__(self, ip):
        self.ip = ip
        self.iplike = '%{}%'.format(self.ip)

    def lookup(self):
        self.dbconnect()
        select_query = (
            "SELECT `name`,`source`,`destination` FROM mytable "
            "WHERE (`source` LIKE ? OR `destination` ? );"
        )

        params = [self.iplike, self.iplike]
        print params
        self.cur.execute(select_query, params)
        print self.cur.fetchall()

实例化:

^{pr2}$

输出:

Traceback (most recent call last):
['%74.121.242.2%', '%74.121.242.2%']
  File "/home/dobbs/shunlibs/IpCleaner.py", line 87, in <module>
    a.palorulelookup()
  File "/home/dobbs/shunlibs/IpCleaner.py", line 81, in lookup
    self.cur.execute(select_query, params)
  File "/usr/lib64/python2.7/site-packages/pymysql/cursors.py", line 164, in execute
    query = self.mogrify(query, args)
  File "/usr/lib64/python2.7/site-packages/pymysql/cursors.py", line 143, in mogrify
    query = query % self._escape_args(args, conn)
TypeError: not all arguments converted during string formatting

Tags: inpyselfipexecutelineargsparams