python查询数据库结果返回


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,),)


注意三者返回的都有区别;


















评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值