Python SQL语法错误:1064,如何修复?
我用python(Twisted)编写了一个Udp服务器,接收Udp消息并更新mysql数据库:Python SQL语法错误:1064,如何修复?,python,mysql,twisted,Python,Mysql,Twisted,我用python(Twisted)编写了一个Udp服务器,接收Udp消息并更新mysql数据库: sql = "update `device` set `msg`='%s', `d_addr`='%s', `d_port`=%d where `did`=%d" %(msg, host, port, r[0]) try: txn.execute(sql) except Exception, e: f = open('./err_log', 'a') f.write('%s\
sql = "update `device` set `msg`='%s', `d_addr`='%s', `d_port`=%d where `did`=%d" %(msg, host, port, r[0])
try:
txn.execute(sql)
except Exception, e:
f = open('./err_log', 'a')
f.write('%s\n' % e)
f.write('%s\n' % sql)
f.close()
错误日志中的错误信息为:
(1064, "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 '220.168.13.132', `d_port`=14058 where `did`=2' at line 1")
update `device` set `msg`='.?F/.ddd?', `d_addr`='220.168.13.132', `d_port`=14058 where `did`=2
因此,我手动执行sql,但没有错误:
MariaDB [kj]> update `device` set `msg`='.?F/.ddd?',
`d_addr`='220.168.13.132', `d_port`=14058 where `did`=2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
消息为远程客户端发送的字符串(18字节),字符串的ascii码为:
0x86 0xAC 0xCF 0x23 0x29 ... 0xE3
参数化查询,忘记与向查询中插入变量相关的SQL语法错误。作为奖励,您正在使您的代码免受以下因素的影响:
@如果您将查询参数化,驱动程序将自动检测类型并处理类型转换。您是否尝试过答案中提供的代码?但是,我不知道为什么会出现sql语法错误
sql = """
UPDATE
device
SET
msg = %s,
d_addr = %s,
d_port = %s
where
did = %s"""
txn.execute(sql, (msg, host, port, r[0]))