Think before you speak, read before you think.

python操作mysql

by

in

yum安装

yum install MySQL-python

使用此模块

import MySQLdb #注意大小写!!

#建立和数据库系统的连接

 conn = MySQLdb.connect(host='localhost', user='root',passwd='root')

#获取操作游标

 cursor = conn.cursor()

#选择数据库

 conn.select_db('python')

#执行SQL,创建一个数据库.

 cursor.execute("""select * from test""")

#获取一条记录,每条记录做为一个元组返回

 result = cursor.fetchone();
 print result
 #print 'ID: %s info: %s' % (result[0],result[1])
 print 'ID: %s info: %s' % result

#获取5条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录

 print "只获取5条记录:"
 results = cursor.fetchmany(5)
 for r in results:
 print r

print “获取所有结果:”
#重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,

 cursor.scroll(0,mode='absolute')
 #获取所有结果
 results = cursor.fetchall()
 for r in results:
 print r
 conn.close()

#关闭连接,释放资源

 cursor.close();

http://www.iteye.com/topic/573092


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *