簡體   English   中英

使用Python進行CRUD…IndexError:元組索引超出范圍

[英]CRUD with Python … IndexError: tuple index out of range

我必須使用Python做幾個選擇和更新。 這是一種全新的語言,在執行以下(簡單)查詢時,我在語法上遇到了一些麻煩:

SELECT A.CUSTOMER_NAME,
A.CUSTOMER_CITY,
B.POPULATION
FROM
CONTRACTS AS A
JOIN CITIES AS B ON
A.CUSTOMER_CITY = B.IDENT
WHERE B.POPULATION <=500000

SELECT A.IDENT,
A.MAKE,
A.MODEL,
A.LUXURY,
B.CAR_IDENT
FROM CARS AS A
JOIN CONTRACTS AS B ON
A.IDENT = B.CAR_IDENT
WHERE LUXURY = 'Y'

UPDATE CONTRACTS
SET BASE_PRICE=1000
WHERE CONTRACT_CLASS >=10

我從更新開始...我認為它比代碼更短...。當我執行更新語句時,出現以下錯誤:

>'update {} set BASE_PRICE = ? where {}'.format(self._table), (row['BASE_PRICE'], >row['where']))
>IndexError: tuple index out of range

這是我的方法

    def retrieve(self, key):
        cursor = self._db.execute('select  from {}'.format(self._table))
        return dict(cursor.fetchone())

    def update(self, row):
        self._db.execute(
            'update {} set BASE_PRICE = ? where {}'.format(self._table), 
            (row['BASE_PRICE'], row['where']))
        self._db.commit()

    def disp_rows(self):
        cursor = self._db.execute('select IDENT, CONTRACT_CLASS, BASE_PRICE from {} order 
        by BASE_PRICE'.format(self._table))
        for row in cursor:
            print('  {}: {}: {}'.format(row['IDENT'], row['CONTRACT_CLASS'], 
            row['BASE_PRICE']))

    def __iter__(self):
        cursor = self._db.execute('select * from {} order by  
        BASE_PRICE'.format(self._table))
        for row in cursor:
            yield dict(row)


    def main():
    db_cities = database(filename = 'insurance.sqlite', table = 'CITIES')
    db= database(filename = 'insurance.sqlite', table = 'CONTRACTS')
    db_cars = database(filename = 'insurance.sqlite', table = 'CARS')

    print('Retrieve rows')
    for row in db: print(row)

    print('Update rows')
    db.update({'where': 'CONTRACT_CLASS' >= 10', 'BASE_PRICE'= 1000})
    for row in db: print(row)

    print('Retrieve rows after update')
    for row in db: print(row)

Thanks in advance for your help!

您在self._table之后放了一個括號。

'UPDATE {table_name} SET BASE_PRICE = {base_price} WHERE {condition}'.format(
     table_name=self._table,
     base_price=row['BASE_PRICE'],
     condition=row['where']
 )

我還做了一些代碼清理。

另一個問題:為什么不使用ORM?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM