python mysql使用executemany()出現(xiàn)TypeError
問(wèn)題描述
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ā)生錯(cuò)誤時(shí)回滾self.db.rollback()except MySQLdb.Error,e: print self.getCurrentTime(),'數(shù)據(jù)庫(kù)錯(cuò)誤,原因%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)以下問(wè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()就沒問(wèn)題。
問(wèn)題解答
回答1:'INSERT INTO %s(%s) VALUES(%s)'
這種寫法是錯(cuò)誤的。占位符 %s 只能出現(xiàn)在值的地方,不能作為表名、字段名出現(xiàn)。.execute* 不會(huì)幫你處理這些東西。
你可以預(yù)先構(gòu)造好合適的 SQL 模板,再傳給 .execute*。前提是,你的表名、字段名是確定不會(huì)有特殊字符的:
fields = ...data = ...sql = ’INSERT INTO {}({}) VALUES(%s)’.format(table, fields)cur.executemany(sql, data)
相關(guān)文章:
1. mysql - 百萬(wàn)行的表中是否盡量避免使用update等sql語(yǔ)句?2. shell - Update query wrong in MySQL3. node.js - mysql如何通過(guò)knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)4. Python從URL中提取域名5. mysql 插入數(shù)值到特定的列一直失敗6. python - 在使用Pycharm時(shí)經(jīng)常看到如下的樣式,小括號(hào)里紅色的部分是什么意思呢?7. javascript - 用jsonp抓取qq音樂(lè)總是說(shuō)回調(diào)函數(shù)沒有定義8. 360瀏覽器與IE瀏覽器有何區(qū)別???9. javascript - 新浪微博網(wǎng)頁(yè)版的字?jǐn)?shù)限制是怎么做的10. 怎么在網(wǎng)頁(yè)中設(shè)置圖片進(jìn)行左右滑動(dòng)
