python mysql使用executemany()出现TypeError
问题描述
def insertData(self,table,param):try: self.db.set_character_set(’utf8’) q= [] for x in param:cols = ’, ’.join(x.keys())values = ’',' ’.join(x.values())q.append((table, cols, ’'’+values+’'’)) sql = 'INSERT INTO %s(%s) VALUES(%s)' try:result = self.cur.executemany(sql,q)insert_id = self.db.insert_id()self.db.commit() except MySQLdb.Error,e:#发生错误时回滚self.db.rollback()except MySQLdb.Error,e: print self.getCurrentTime(),'数据库错误,原因%d: %s' % (e.args[0], e.args[1])
其中q的部分内容为[(’houseurl’, ’url’, u’'/ershoufang/szlh11469938.html'’), (’houseurl’, ’url’, u’'/ershoufang/szlh11470634.html'’)]
执行以上代码后,出现以下问题:
29 sql = 'INSERT INTO %s(%s) VALUES(%s)' 30 try:---> 31 result = self.cur.executemany(sql,q) 32 insert_id = self.db.insert_id() 33 self.db.commit()/usr/lib/python2.7/dist-packages/MySQLdb/cursors.pyc in executemany(self, query, args) 274 self.errorhandler(self, ProgrammingError, msg.args[0]) 275 else:--> 276 self.errorhandler(self, TypeError, msg) 277 except (SystemExit, KeyboardInterrupt): 278 raise/usr/lib/python2.7/dist-packages/MySQLdb/connections.pyc in defaulterrorhandler(***failed resolving arguments***) 34 del connection 35 if isinstance(errorvalue, BaseException):---> 36 raise errorvalue 37 if errorclass is not None: 38 raise errorclass(errorvalue)TypeError: not all arguments converted during string formatting
但是我一条条插入使用execute()就没问题。
问题解答
回答1:'INSERT INTO %s(%s) VALUES(%s)'
这种写法是错误的。占位符 %s 只能出现在值的地方,不能作为表名、字段名出现。.execute* 不会帮你处理这些东西。
你可以预先构造好合适的 SQL 模板,再传给 .execute*。前提是,你的表名、字段名是确定不会有特殊字符的:
fields = ...data = ...sql = ’INSERT INTO {}({}) VALUES(%s)’.format(table, fields)cur.executemany(sql, data)
相关文章:
1. 如何解决Centos下Docker服务启动无响应,且输入docker命令无响应?2. spring-mvc - spring-session-redis HttpSessionListener失效3. docker images显示的镜像过多,狗眼被亮瞎了,怎么办?4. Docker for Mac 创建的dnsmasq容器连不上/不工作的问题5. docker网络端口映射,没有方便点的操作方法么?6. docker api 开发的端口怎么获取?7. docker容器呢SSH为什么连不通呢?8. 前端 - 类到底该如何去命名 .newsList 这种的命名难道真的不是过度语义化吗?~9. docker start -a dockername 老是卡住,什么情况?10. Hbuilder中的phpMyAdmin访问题

网公网安备