红联Linux门户
Linux帮助

mysql unsupported operand type(s) for %:'tuple' and 'tuple'

发布时间:2016-10-14 10:08:36来源:linux网站作者:heybob
环境:ubuntu14.04,python2.7
这篇文章只是为了记录我碰到的一个MySQL相关的小问题。
 
学习爬虫,看到一个项目:https://github.com/airingursb/bilibili-report
mysql unsupported operand type(s) for %:'tuple' and 'tuple'
 
看了下代码,就是爬取bili用户信息后保存到mysql中。因为想之后方便提取mysql里的信息,所以将mysql相关的代码修改,放到另一个模块。
 
其中添加数据的代码如下:
class Ch_mysql():  
def __init__(self):  
self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='user',  
passwd='passwd', db=database, charset='utf8')  
def add(self, kwargs):  
mid = kwargs.get('mid', None)  
name = kwargs.get('name', None)  
sex = kwargs.get('sex', None)  
face = kwargs.get('face', None)  
coins = kwargs.get('coins', None)  
regtime = kwargs.get('regtime', None)  
spacesta = kwargs.get('spacesta', None)  
birthday = kwargs.get('birthday', None)  
place = kwargs.get('place', None)  
description = kwargs.get('description', None)  
article = kwargs.get('article', None)  
fans = kwargs.get('fans', None)  
friend = kwargs.get('friend', None)  
attention = kwargs.get('attention', None)  
sign = kwargs.get('sign', None)  
attentions = kwargs.get('attentions', None)  
level = kwargs.get('level', None)  
exp = kwargs.get('exp', None)  
sql = "INSERT INTO bilibili_user_info VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"  
try:  
cur = self.conn.cursor()  
cur.execute(sql, (mid, mid, name, sex, face, coins, regtime, spacesta, birthday, place, description,  
article, fans, friend, attention, sign, str(attentions), level, exp))  
cur.close()  
# raise  # for test  
self.conn.commit()  # commit之后raise不会回滚了  
except Exception, e:  
print 'db Exception: ', e  
self.conn.rollback()  
finally:  
# cur.close()  
# self.conn.commit()  
self.conn.close()  
 
这是改好的代码,之前代码中sql因为用的单引号,所以一直报错:unsupported operand type(s) for %: 'tuple' and 'tuple'
 
查了些文章说是Python的问题,搞不清原因,后来照以前的代码意义对比,将单引号改为双引号后就好了。
 
本文永久更新地址:http://www.linuxdiyf.com/linux/25022.html