国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python mysql使用executemany()出現(xiàn)TypeError

瀏覽:143日期:2022-08-01 09:27:08

問題描述

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:#發(fā)生錯誤時回滾self.db.rollback()except MySQLdb.Error,e: print self.getCurrentTime(),'數(shù)據(jù)庫錯誤,原因%d: %s' % (e.args[0], e.args[1])

其中q的部分內(nèi)容為[(’houseurl’, ’url’, u’'/ershoufang/szlh11469938.html'’), (’houseurl’, ’url’, u’'/ershoufang/szlh11470634.html'’)]

執(zhí)行以上代碼后,出現(xiàn)以下問題:

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 只能出現(xiàn)在值的地方,不能作為表名、字段名出現(xiàn)。.execute* 不會幫你處理這些東西。

你可以預(yù)先構(gòu)造好合適的 SQL 模板,再傳給 .execute*。前提是,你的表名、字段名是確定不會有特殊字符的:

fields = ...data = ...sql = ’INSERT INTO {}({}) VALUES(%s)’.format(table, fields)cur.executemany(sql, data)

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 景宁| 上虞市| 阿克陶县| 维西| 额济纳旗| 屯留县| 曲沃县| 互助| 惠州市| 忻城县| 阳西县| 疏勒县| 通榆县| 丹凤县| 门头沟区| 惠安县| 慈溪市| 揭东县| 类乌齐县| 山丹县| 邢台县| 宁河县| 遂川县| 玉屏| 杭锦后旗| 营山县| 五家渠市| 虹口区| 波密县| 富源县| 勃利县| 五原县| 白水县| 丹江口市| 吐鲁番市| 磴口县| 富阳市| 邻水| 临夏市| 辽源市| 靖宇县|