>  Q&A  >  본문

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()就没问题。

巴扎黑巴扎黑2741일 전674

모든 응답(1)나는 대답할 것이다

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:35:38

    으아아아

    이렇게 쓰는 방식은 잘못되었습니다. 자리 표시자 %s는 값으로만 ​​표시될 수 있으며 테이블 이름이나 필드 이름으로 표시될 수 없습니다. .execute*는 이 작업을 처리하지 않습니다.

    적절한 SQL 템플릿을 미리 구성하여 .execute*에 전달할 수 있습니다. 전제는 테이블 이름과 필드 이름에 특수 문자가 포함되어서는 안 된다는 것입니다.

    으아아아

    회신하다
    0
  • 취소회신하다