# -*- coding: utf-8 -*-
import sys
import MySQLdb
try:
conn
=MySQLdb.connect(host="localhost",user="root",passwd="xxx")
except Exception,e:
print e
sys.exit()
#获取操作游标
cursor=conn.cursor()
#执行SQL,创建一个数据库.
cursor.execute("""create database if not exists zhsen DEFAULT CHARACTER SET utf8 COLLATE utf8_bin""")
conn.select_db(
'zhsen')
#执行SQL,创建一个数据表.
sql="create table if not exists test1(name varchar(128),age int(4))"
cursor.execute(sql)
#cursor.execute("insert into test1(name,age)values('haha',22)")
#
conn.commit()
count=cursor.execute("select * from test1")

#重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,
cursor.scroll(0,mode='absolute')
#获取所有结果
results = cursor.fetchall()
if results:
print '总共有%s条记录',count
for r in results:
print r,'%s,%s'%(r[0],r[1])
else:
print "未检索出记录!"
cursor.close()
conn.close()

当第一次创建表,没有任何记录的时候,cursor.scroll(0,mode='absolute')如果加上,报错:

Traceback (most recent call last):
  File "C:\Documents and Settings\Administrator\桌面\test.py", line 22, in <module>
    cursor.scroll(0,mode='absolute')
  File "D:\Python26\Lib\site-packages\MySQLdb\cursors.py", line 364, in scroll
    self.errorhandler(self, IndexError, "out of range")
  File "D:\Python26\Lib\site-packages\MySQLdb\connections.py", line 35, in defaulterrorhandler
    raise errorclass, errorvalue
IndexError: out of range