python MySQLdb DictCursor使用实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb import MySQLdb.cursors import sys
#解决编译器运行,UnicodeEncodeError: 'ascii' codec can't encode characters in position reload(sys) sys.setdefaultencoding( "utf-8" )
db= MySQLdb.connect(host="localhost",port = 3306,user="root",passwd="root", db="test",charset='utf8') cursor = db.cursor(MySQLdb.cursors.DictCursor)
sql = "select * from py_user" try: cursor.execute(sql) results = cursor.fetchall() # print results for row in results: name = row['name'] address = row['address'] print "姓名:%s,地址:%s" %(name,address) except: print "Error: unable to fecth data"
cursor.close() # 关闭数据库连接 db.close()
|
近期评论