您好我正在尝试使用Python参数化MySQL查询。有时我传入的值是NoneType
或NULL
。
在mysql中使用NULL
或NoneType
值时,为什么%s
或%d
不适用于下面的插入查询?
class DBWork(object):
def __init__(self, attackerip=None, victimip=None, shunlen=15, shuncount=1, shunreason=None, shunepoch=None,
shunerrorbool=False, shunerror=None, paloaddedepoch=None, paloremovedepoch=None,
lastshunlen=15):
self.Id = None
self.attackerip = attackerip
self.victimip = victimip
self.shunlen = shunlen
self.shuncount = shuncount
self.shunreason = shunreason
self.shunepoch = shunepoch
self.shundatetime = 'need to build this'
self.shunerrorbool = shunerrorbool
self.shunerror = shunerror
self.paloaddedepoch = paloaddedepoch
self.paloremovedepoch = paloremovedepoch
self.lastshunlen = lastshunlen
self.shunlen = shunlen
self.newshunlen = lastshunlen * shuncount
...
def HistoryInsert(self):
insert_query = (
"INSERT INTO `autoshun`.`shunhistory` "
"(Id, attackerip, victimip, shunlen, shuncount, shunreason, shunepoch, shundatetime, shunerrorbool, "
"shunerror, paloaddedepoch, paloremovedepoch) "
"VALUES "
"(NULL, %s, %s, %d, %d, %s, %s, %s, %s, %s, %s, %s );"
)
values = [None, self.attackerip, self.victimip, self.shunlen, self.shuncount, self.shunreason, self.shunepoch,
self.shundatetime, self.shunerrorbool, self.shunerror, self.paloaddedepoch, self.paloremovedepoch]
return self.cur.execute(insert_query, values)
sample = DBWork(attackerip='1.1.1.15', victimip='2.2.2.2', shunreason='hax', shuncount=1, )
#
sample.DBConnect()
sample.HistoryInsert()
(values
列表的调试)
<type 'list'>: [None, '1.1.1.15', '2.2.2.2', 15, 1, 'hax', None, 'need to build this', False, None, None, None]
/usr/bin/python2.7 /home/dobbs/PycharmProjects/autoshun/sqlobjects.py
Traceback (most recent call last):
File "/home/dobbs/PycharmProjects/autoshun/sqlobjects.py", line 100, in <module>
sample.HistoryInsert()
File "/home/dobbs/PycharmProjects/autoshun/sqlobjects.py", line 93, in HistoryInsert
return self.cur.execute(insert_query, values)
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: %d format: a number is required, not str