游标
游标提供了一种对从表中检索出的数据进行操作的灵活手段,游标实际上是一种能从包括多条数据记录的结果集中每次提取一条记录的机制。游标总是与一条SQL选择语句相关联因为游标由结果集(可以是零条、一条或相关的选择语句检索出的多条记录)和结果集中指向特定记录的游标位置组成。当决定对结果集进行处理时,必须声明一个指向该结果集的游标。
常用方法:
cursor():创建游标对象
close():关闭此游标对象
fetchone():得到结果集的下一行
fetchmany([size=cursor.arraysize]):得到结果集的下几行
fetchall():得到结果集的所有行
execute(sql[,args]):执行一个 数据库查询或命令
executemany(sql,args):执行多个数据库查询或命令
例子:
connect.py
#!/usr/bin/env python#coding:utf8
importMySQLdbdefconnect_mysql():
db_config={"host":"127.0.0.1","port":3306,"user":"root","passwd":"123456","db":"world","charset":"utf8",
}try:
cnx= MySQLdb.connect(**db_config)exceptException as e :raiseereturn cnx
#!/usr/bin/env python#coding:utf8
importMySQLdbfrom connect importconnect_mysqlif __name__ == "__main__":
sql= "select * from city"cnx=connect_mysql()
cus=cnx.cursor()#print(dir(cus))
try:
cus.execute(sql)
result=cus.fetchone()print(result)
result1= cus.fetchmany(3)print(result1)#result3 = cus.fetchall()
#print(result3)
cus.close()exceptException as e :
cnx.rollback()raiseefinally:
cnx.close()
mysql连接池
Python DBUtils
DBUtils是一套Python数据库连接池包,并允许对非线程安全的数据库接口进行线程安全包装。DBUtils来自Webware for Python。
DBUtils提供两种外部接口:
PersistentDB :提供线程专用的数据库连接,并自动管理连接。
PooledDB :提供线程间可共享的数据库连接,并自动管理连接。
下载地址:http://www.webwareforpython.org/downloads/DBUtils/
或者Pip install DBUtils
例子:
#!/usr/bin/env python#coding:utf8
importMySQLdbfrom DBUtils.PooledDB importPooledDB
db_config={"host": "127.0.0.1","port": 3306,"user": "root","passwd": "123456","db": "world","charset": "utf8",
}
pool= PooledDB(MySQLdb,5,**db_config)if __name__ == "__main__":
cnx=pool.connection()
cus=cnx.cursor()
sql= "select * from city"
try:
cus.execute(sql)
result=cus.fetchone()print(result)
cus.close()
cnx.commit()exceptException as e :raiseefinally:
cnx.close()
运行结果:
(1L, u'Kabul', u'AFG', u'Kabol', 1780000L)