0

我必须使用 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!
4

1 回答 1

1

您在 . 之后放错了一个括号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?

于 2013-02-21T20:14:15.567 回答