连接 MySQL 报错'NoneType' object has no attribute '__getitem__'

2016-07-14 15:25:48 +08:00
 hhp
新手一枚,想批量获取一批数据在后台自动生成的 ID 然后做匹配
本来是 for 循环,报错后拆开来还是报错那应该不是我循环的问题了
第一段能正常获取到 ID ,为什么第二段始终返回 NONE

Traceback (most recent call last):
File "add_store.py", line 119, in <module>
main()
File "add_store.py", line 113, in main
print result[0]
TypeError: 'NoneType' object has no attribute '__getitem__'

代码如下:
(删掉了括号里的敏感信息)
hosturl =
posturl =
posturl2 =
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
h = urllib2.urlopen(hosturl)
headers = {}
postData = {}
postData = urllib.urlencode(postData)
request = urllib2.Request(posturl, postData, headers)
response = urllib2.urlopen(request)

conn = MySQLdb.connect()

def main():
i = 31
stname = 'teststore' + str(i)
postData2 = {'storeName': stname}
postData2 = urllib.urlencode(postData2)
request2 = urllib2.Request(posturl2, postData2, headers)
response2 = urllib2.urlopen(request2)
cur = conn.cursor()
cur.execute("select a.store_id from store as a where a.store_name = %s", [stname])
print stname
result = cur.fetchone()
print result[0]

i = 32
stname = 'teststore' + str(i)
postData2 = {'storeName': stname}
postData2 = urllib.urlencode(postData2)
request2 = urllib2.Request(posturl2, postData2, headers)
response2 = urllib2.urlopen(request2)
cur.execute("select a.store_id from store as a where a.store_name = %s", [stname])
print stname
result = cur.fetchone()
print result[0]
cur.close()

conn.close()

if __name__ == '__main__':
main()
9489 次点击
所在节点    Python
11 条回复
hhp
2016-07-14 15:43:37 +08:00
有大神知道为什么吗(星星眼
myyou
2016-07-14 16:02:31 +08:00
你 result 返回的是 None ,所以 result [0] 取不了值
hhp
2016-07-14 16:16:01 +08:00
@myyou 对,我就是在问为什么返回 none 了,第一段里都是正常的,第二段 sql 在数据库里也是有记录的
myyou
2016-07-14 16:34:20 +08:00
@hhp 你 store_name 应该没有叫 teststore32 的吧
hhp
2016-07-14 16:47:49 +08:00
@myyou 有的,查了,是成功写到表里了
上面的 31 就有,两段代码是一样的
hhp
2016-07-14 17:10:41 +08:00
@myyou 我总觉得是 fetchone 的问题,但网上查了半天都没找到确切原因
dozer47528
2016-07-14 17:12:31 +08:00
@hhp 你能看一下两次 execute 的返回值是什么吗?
我和你有类似的问题,未解决: http://stackoverflow.com/questions/38241440/python-mysqldb-execute-result-doesnt-match-fetch-result
dozer47528
2016-07-14 17:13:31 +08:00
@hhp 我是用了连接池后出现问题的,而你的代码里多次查询用了同一个连接,所以其实和我情况类似。
dozer47528
2016-07-14 17:19:38 +08:00
@hhp 可以加我个QQ 41709580
hhp
2016-07-14 17:25:24 +08:00
@dozer47528 第一次是 1 第二次是 0 ,但是数据库里实际上是有查询结果的
dozer47528
2016-07-14 17:27:23 +08:00
@hhp 那我和你不一样,我 2 次都是 1 ,但 fetchone 确是 None

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/292502

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX