python mysql数据库做insert操作时报_mysql_exceptions.ProgrammingError,,运行环境:python:
python mysql数据库做insert操作时报_mysql_exceptions.ProgrammingError,,运行环境:python:
运行环境:
python:3.2
mysql:5.6
系统:win7
python代码:
import MySQLdbcon = MySQLdb.connect(host='localhost', user='root', passwd='root', db='hr_resume_center', charset='utf8')cursor = con.cursor()sql = "INSERT INTO hr_resume_core (resume_id,name,mobile,email,add_time,sys_time,version) VALUES(%s,%s,%s,%s,%s,%s,%s)"param = [1,'bright','13641154657','jackieming\@sina.cn',1385625423,1385625423,1]cursor.execute(sql,param)cursor.close()con.close()
报错:
Traceback (most recent call last): File "E:\python\mysqldb\demo1\demo_insert.py", line 10, in <module> cursor.execute(sqls,param) File "D:\Python32\lib\site-packages\MySQLdb\cursors.py", line 184, in execute self.errorhandler(self, exc, value) File "D:\Python32\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass(errorvalue)_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 '%s,%s,%s,%s,%s,%s,%s)' at line 1")
问题
我查过好多资料都显示可以使用%s的占位符方式执行sql,为什么我使用这种方式总是报错?通过错误提示看好像是sql语句的问题,希望有人能指导一下。
param should be a tuple, other than a list.
我真想说一句:如果以后再提问有关MySQL的问题,帖代码的同时,必须贴一下表格的结构!!!(要不然你让别人怎么运行你的代码!!!)
CREATE TABLE IF NOT EXISTS `hr_resume_core` ( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `resume_id` bigint(20) unsigned NOT NULL, `name` varchar(100) NOT NULL, `mobile` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `add_time` int(11) NOT NULL, `sys_time` int(11) NOT NULL, `version` int(11) NOT NULL, PRIMARY KEY (`ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
改圆括号之后和%s有关的错误确实消失了,但记录插入不进去(也不报错),执行了和没执行一样。
其实是最后关闭连接前少了一句con.commit()。MySQLdb默认会采用事务,也就是说整套SQL操作做完了,必须提交事务才能真正写入。——你可以把表格的存储引擎改成MyISAM(这个引擎不支持事务),就可以看到不需要con.commit()就可以正确插入。
我的试验环境是Py2.7。我想不起来MySQLdb是否支持Py3K了,你可以装一个2.7试试看是不是版本问题。
方括号(list)改圆括号(tuple)。
这里是MySQLdb的行为在作祟。MySQLdb认为list是用来干这个的:
param = [(1,'bright','13641154657','jackieming\@sina.cn',1385625423,1385625423,1),(2,'bright','13641154657','jackieming\@sina.cn',1385625423,1385625423,1),(3,'bright','13641154657','jackieming\@sina.cn',1385625423,1385625423,1),]
这相当于一次插入多条记录。我事实上很不喜欢这种方式——如果只是tuple和list的区别,就可以如此彻底的影响语义,可以说这种设计是绝对失败的。彻底违反直觉,不仅不能自表意,甚至“逆向”回去把语义“藏”起来,这让我无法理解。
话说MySQLdb支持Py3K了吗?
编橙之家文章,
相关内容
- python能把带等号的字符串转换成字典类型吗,python等号
- python jinja2模板语言获取javascript function(_index) 传过来的
- Python web开发给controller、action附加属性如何操作,pyth
- 请问Python语言中is与双等号==有什么区别及作用,pytho
- Python终端中能输出带颜色的字符吗?,python终端,今天看
- Python语言method_descriptor语法正确解释是?,,type(str.cen
- Python字符串转数字有没有更好的方法,python字符串,py
- python Burpsuite,Wireshark,Fiddler 抓包的适用场景,以及优
- Python Django生成admin页中禁止模块部分功能如何实现,
- python sort()中cmp参数有什么要求,pythoncmp,最近在看<
评论关闭