一、
Doingitthehardway:
cur.execute("select*fromorderswherecustomer_num=104") row=cur.fetchone()
whilerow!=None:
print"Order%swasplacedon%s."%(row[0],row[1])
row=cur.fetchone()
Usingcursorsasiteratorsismucheasier:
cur.execute("select*fromorderswherecustomer_num=104") forrowincur:
print"Order%swasplacedon%s."%(row[0],row[1])
二、
ColumnAccessAlternatives
Bydefault,rowsarereturnedastuplesaccordingtoDB-APIstandard,which
requirescolumnaccessbynumber.Dictionarycursorsreturnrowsas
dictionariesthatallowcolumnaccessbyname:
dictcur=conn.cursor(rowformat=informixdb.ROW_AS_DICT)
dictcur.execute("select*fromorderswherecustomer_num=104") forrowindictcur:
print"Order%swasplacedon%s.”,(row['order_num'],
row['order_date'])
Objectcursorsofferamoreconcisewayofaccessingcolumnsbyname:
objcur=conn.cursor(rowformat=informixdb.ROW_AS_OBJECT)
objcur.execute("select*fromorderswherecustomer_num=104") forrowinobjcur:
print"Order%swasplacedon%s."%(row.order_num,
row.order_date)
三、NamedCursor
Explicitlynamedcursorsareusefulasupdateordeletecursors:
price_increase={'SMT':4,'HSK':5,'SHM':3}
updcur=conn.cursor(name="updcur",rowformat=informixdb.ROW_AS_OBJECT)
updcur.execute("select*fromstockforupdateofunit_price")
forrowinupdcur:
increase=price_increase.get(row.manu_code,None)
ifincrease!=None:
newprice=row.unit_price*(1.0+increase/100.0)
cur.execute("updatestocksetunit_price=?wherecurrentofupdcur",
[newprice])
四、BulkExecution
names=[
(“Jonathan”,“Leffler”),
(“Darryl”,“Priest”),
(“Carsten”,“Haese”)
]
cur.executemany(“””
insertintocustomer(fname,lname)values(?,?) “””,names)
Forinsertstatements,executemanyemploysaninsertcursor“underthehood”when
possible.
五、PreparedStatements
get_manu_name=conn.cursor()
get_manu_name.prepare(“””
selectmanu_namefrommanufactwheremanu_code=? “””)
whileTrue:
manu_code=raw_input(“Enteramanufacturercode:“)
ifmanu_code==””:break
get_manu_name.execute(None,[manu_code])
manu_name=get_manu_name.fetchone()[0]
printmanu_name
六、ScrollCursor
scrollcurs=conn.cursor(scroll=True)
scrollcurs.execute(“select*fromcustomerorderbycustomer_num”) scrollcurs.scroll(10,”absolute”)
printscrollcurs.fetchone()
scrollcurs.scroll(-5,”relative”)
printscrollcurs.fetchone()
七、ErrorHandling
ydefault,errorconditionsraisePythonexceptions:
my_sqlcode=0
try:
cur.execute("sleect*fromsystables") exceptinformixdb.Error,e:
my_sqlcode=e.sqlcode
printmy_sqlcode
Anerrorhandlercallbackcanbesetuptocustomizeerrorhandling.