Psycopg2执行元组索引超出范围错误

3

我对Python非常陌生,这是我学习的第一门编程语言。同时,这也是我第一次尝试使用SQL和psycopg2。任何“愚蠢”的建议都会受到欢迎!

我不确定问题出在哪里。我的研究告诉我,我给cursor.execute(INSERT...传递的参数过少或过多,但我已经尝试了许多不同的计数,似乎都无法正常工作。从我的角度来看,cursor.execute(CREATE...创建了一个具有6个列的表格,而我正在向它传递6个参数。

from lxml import html  # Used to parse XML
import requests #used to service API request

itemtypeid1 = 34
itemtypeid2 = 35
regionid = 10000002

webpage = requests.get('http://api.eve-central.com/api/marketstat?typeid=%i&typeid=%i&regionlimit=%i' % (
itemtypeid1, itemtypeid2, regionid))

if webpage.status_code == 200:
    data = html.fromstring(webpage.content)
    for item in data.iter('type'):


        buy_dict = {node.tag: node.text for node in item.xpath("buy/*")}
        sell_dict = {node.tag: node.text for node in item.xpath("sell/*")}

        #Variables for output
        itemid = (item.get("id"))
        buymin = buy_dict['min']
        buymax = buy_dict['max']
        buymedian = buy_dict['median']
        buyvolume = buy_dict['volume']
        buyaverage = buy_dict['avg']

#Fail if api webpage unavaliable
else:
        print "Webpage unavaliable"
        Webpage.raise_for_status()


#############################################################################


import psycopg2

connection = psycopg2.connect(database='evemarketdata', user='postgres', password='black3car')

#open a cursor to perform DB operations
cursor = connection.cursor()

#create new table
cursor.execute("CREATE TABLE arkonor (itemid integer primary key, min integer, max integer, median integer, volume integer, average integer);")

#Insert row data into DB table
cursor.execute("""INSERT INTO arkonor (typeid, min, max, median, volume, average)
     VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
     ('itemid', 'buymin', 'buymax', 'buymedian', 'buyvolume', 'buyaverage'))


#Commits all changes does with cursor
#connection.commit()

导致
 Traceback (most recent call last):

 File "E:\Eve Spreadsheets\Python\PostgreConnect.py", line 49, in <module>

('itemid', 'buymin', 'buymax', 'buymedian', 'buyvolume', 'buyaverage'))

IndexError: tuple index out of range

只是路过想提醒您:在“INSERT”的执行语句中,实际上您正在向查询传递6个字符串。您需要传递变量的值(即,不带引号)。 - Flickerlight
1个回答

7
您的查询中有8个参数,但元组中只提供了6个字段。代码应该是这样的:
#Insert row data into DB table
cursor.execute("""INSERT INTO arkonor (typeid, min, max, median, volume, average)
     VALUES (%s, %s, %s, %s, %s, %s)""",
     ('itemid', 'buymin', 'buymax', 'buymedian', 'buyvolume', 'buyaverage'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接