当cur.execute()
和db.commit()
行被注释掉时,此代码可以正常工作;即如果我所做的只是打印查询,则该程序运行n行。问题似乎发生在这里:
player_categories_statistics = cur.fetchone()
player_id = player_categories_statistics[0]
当我尝试插入结果时,我得到:
Traceback (most recent call last):
File "test2.py", line 72, in <module>
meat = meatgrind(league_name, categories_measurement_statistics)
File "test2.py", line 32, in meatgrind
player_id = int(player_categories_statistics[0])
TypeError: 'NoneType' object is not subscriptable
代码:
import sys
import MySQLdb
import string
db = MySQLdb.connect()
cur = db.cursor('localhost','me',XXXXX,'testdb')
def meatgrind(league_name,categories_measurement_statistics):
# a varied range of different categories can be used
# 1. list categories
categories = []
categories_string = "player_id"
categories_string_newtable = "meatgrinded_player_id, player_id"
for category in categories_measurement_statistics:
categories_string += ", " + category[0]
categories_string_newtable += ", " + category[0]
# 2. get players and statistics
query = "SELECT %s FROM players" % (categories_string)
cur.execute("%s" % (query))
# rowcount = int(cur.rowcount)
rowcount = 2 #hard-coded for debugging
# 3. meatgrind one player at a time
meatgrinded_player_id = 1
for i in range(rowcount):
player_categories_statistics = cur.fetchone()
player_id = player_categories_statistics[0]
#4. grind a category statistic
meatgrindings_string = "%d, %d" % (meatgrinded_player_id, player_id)
index = 1
for category in categories_measurement_statistics:
# SOME MATH HERE resulting in player_meatgrindings
meatgrindings_string += ", %0.4f" % player_meatgrindings
query = """INSERT INTO sometable (%s) VALUES (%s)""" % (categories_string_newtable, meatgrindings_string)
cur.execute("%s" % (query))
db.commit()
meatgrinded_player_id += 1
league_name = 'test'
categories_measurement_statistics = (('H', 156.3, 19.643093216474604), ('HR', 21.3, 9.003147597738618), ('SB', 13.25, 16.041179646286754))
meat = meatgrind(league_name, categories_measurement_statistics)
答案 0 :(得分:3)
您的错误原因是:
player_categories_statistics = cur.fetchone()
这会将player_categories_statistics
设置为None
。 None[0]
提出异常。
这种情况发生的唯一原因是您的查询不返回任何行,这意味着您的表为空。您的表很可能是空的,因为您从未在其中放置任何行,或者您不太可能以某种方式删除它们。
我的罪魁祸首可能如下,您正在插入sometable
并从players
中选择:
INSERT INTO sometable (%s) VALUES (%s)
VS
SELECT %s FROM players
这是可能的唯一原因是因为即使行没有返回任何内容,你也强迫它循环:
rowcount = 2 #hard-coded for debugging
其他信息:
这是我在sqlite3数据库上运行的一个工作查询,其中包含一个单独的表,其中包含与您的语句几乎相同的语句,只是为了表明如果数据确实在那里,您的工作应该正常工作。
query = "SELECT %s FROM customer" % 'first_name, last_name'
row = c.execute("%s" % (query)).fetchone()
row
Out[28]: (u'Derek', u'Litz')
这是另一个在sqlite3数据库上使用另一个表而没有行的查询。
query = "SELECT %s FROM customer2" % 'first_name, last_name'
print c.execute("%s" % (query)).fetchone()
None
如您所见,与上述行为相同。
还要确保rowcount以您想要的方式使用您的数据库。例如,它不适用于sqlite3。请参阅http://www.python.org/dev/peps/pep-0249/#cursor_objects中的rowcount规范并查阅MySQLdb文档。