python操作数据库,在查询中遇到几个令人恶心的问题,语句都没问题,就是报错。
sql_user_item_operationsdays = sql_user_item_operationsdays = 'select sum(opernum) as numbers from %s where user_id=%d and behavior_type=%d and diffdays>%d'
usertype = [2]#[1,2,3,4]
dayList = [26]#[26, 22, 15, 8, 0]
for type_line in usertype:
for day_line in dayList:
sql = sql_user_item_operationsdays % (filename, user_id, type_line, day_line)
print sql
sqlnum = self.cur.execute(sql)
print 'sqlnum is %d' % sqlnum
result = self.cur.fetchone()
print 'result is ' + result
temp = self.result_fetch(sqlnum, result)
print 'temp is %d' % temp
user_featuresList.append( float(temp))
上面代码是我写的一个提取特征部分代码,最终发现原来是cur.execute()执行sql语句返回结果的问题;一般情况sqlnum=cur.execute(sql),
sql语句若查不到结果,返回0;但是上面怎么就不返回0,而是返回1,我再三验证,原来还真是1,但是result=cur.fetchone()返回的却是((None,),),
最终发现select sum()这里返回时,若查不到会返回1,但是result元组中存的是NontType类型变量None,因此程序一直报错。
conn = mysqldb.connect(host='localhost', user='root',passwd='',port=3306)
cur = conn.cursor()
conn.select_db('tianchi_420')
sql1 = 'select sum(opernum) from user_item_operations29days where user_id=100509623 and behavior_type=2 and diffdays>26';
print sql1
sqlnum = cur.execute(sql1)
print sqlnum
result = cur.fetchall()
print result
print '----------------------------'
sql1 = 'select * from user_item_operations29days where user_id=100509623 and behavior_type=2 and diffdays>26';
print sql1
sqlnum = cur.execute(sql1)
print sqlnum
result = cur.fetchall()
print result
print '----------------------------'
sql1 = 'select count(*) from user_item_operations29days where user_id=100509623 and behavior_type=2 and diffdays>26';
print sql1
sqlnum = cur.execute(sql1)
print sqlnum
result = cur.fetchall()
print result
print '-------------------------------'
结果如下:
select sum(opernum) from user_item_operations29days where user_id=100509623 and behavior_type=2 and diffdays>26
1
((None,),)
----------------------------
select * from user_item_operations29days where user_id=100509623 and behavior_type=2 and diffdays>26
0
()
----------------------------
select count(*) from user_item_operations29days where user_id=100509623 and behavior_type=2 and diffdays>26
1
((0L,),)
注意三者返回的都有区别;