与Python的CRUD ... IndexError:元组索引超出范围

与Python的CRUD ... IndexError:元组索引超出范围

问题描述:

我必须做一些使用Python的选择和更新。全新这个语言,我有做以下的(简单)查询时有点麻烦的语法:与Python的CRUD ... IndexError:元组索引超出范围

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! 

您后放错位置的支架。

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

我也做了一些代码清理。

另一个问题:为什么不使用ORM?

+0

很酷,这工作!现在转到其他2个查询。 – engr007 2013-02-21 20:27:05

+0

你现在已经明白'format()'的用法了吗?我在大括号中使用名称的事实更多是一种习惯,没有它们也行得通,但是不可读。 – floqqi 2013-02-21 20:31:00

+0

是的,格式很容易理解 – engr007 2013-02-21 20:41:52