开发者社区> 问答> 正文

python mysql插入数据出错的问题,也是关于处理字符串中特殊字符的问题?报错

python操作mysql时候报错

import MySQLdb

conn=MySQLdb.connect(host='localhost',user='root',passwd='123')
cursor=conn.cursor()
u='3'
bb='<b>3:1</b>'
cursor.execute('insert into bu.test (id,log) values (%s,%s)'% (str(u),bb) )
conn.commit()
cursor.close()
conn.close()
之后会报错

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<b>3:1</b>)' at line 1")

如果把变量bb的值改为bb='3:1'会报以下错误

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':1)' at line 1")

所以知道肯定是bb的字符串中的特殊字符在捣蛋,这个怎么处理

bb=r'3:1' 也不行

如何处理,麻烦帮忙,谢谢啊

展开
收起
爱吃鱼的程序员 2020-06-14 14:43:52 1381 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    不要用%或者+操作符来拼接SQL语句,应该使用占位符。即execute的第二个参数。

    cursor.execute('insertintobu.test(id,log)values(%s,%s)',(str(u),bb))

    参考: http://stackoverflow.com/a/775399

    +1最外边用双引号也不对bb外边再加个双引号
    2020-06-14 14:44:07
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载