我必须使用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语句时,出现以下错误:
>'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!
答案 0 :(得分: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?