python - SQL语法错误:1064,如何修复?

标签 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\n' % e)
    f.write('%s\n' % sql)
    f.close()

err_log中的错误信息是:

(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

msg是远程客户端发送的字符串(18字节),字符串的ascii码是:

0x86 0xAC 0xCF 0x23 0x29 ... 0xE3

最佳答案

参数化查询并忘记与将变量插入查询相关的 SQL 语法错误。作为奖励,您可以使您的代码免受 SQL injection attacks 的侵害。 :

sql = """
    UPDATE
        device 
    SET 
        msg = %s, 
        d_addr = %s, 
        d_port = %s 
    where 
        did = %s"""
txn.execute(sql, (msg, host, port, r[0]))

关于python - SQL语法错误:1064,如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36299070/

相关文章:

python - 如何在 Django 中序列化多个对象

php - 加密的注册和登录密码出错

mysql - 从上个月的价格变化表中获取最后 2 条更新的unit_price

mysql - 用于在 MATLAB 中处理的图像数据库

python - 从 Twisted 调用 Python 代码

python - 调用reactor.stop时Twisted不会退出

Python Twisted : SSL routines , ssl3_get_server_certificate 错误

Python如何制作 "associative array"

python - 我如何在 Python 中的两个不同进程之间共享一个串口

python - Python 中的构造函数