python如何连接mysql
主要使用了MySQLdb
代码部分
__author__ = 'chunlongyuan'
import MySQLdb
import urllib2
import time
host = "localhost"
user = "root"
password = "root"
db = "test_db"
pageSize = 10
try:
conn = MySQLdb.connect(host, user, password, db)
except Exception, e:
print "连接数据库失败"
exit(0)
startTime = time.time()
try:
cursor = conn.cursor()
for page in range(1, 10):
start = (page - 1) * pageSize
sql = "select field1,field2 from tablename limit %d, %d" % (start, pageSize)
print sql
cursor.execute(sql)
data = cursor.fetchall()
if len(data) > 0:
for fields in data:
field1 = fields[0]
else:
break
print '执行完成,耗时(s):%d' % ((time.time() - startTime) / 1000)
except Exception:
print "处理时出现异常"
finally:
cursor.close()
conn.close()
file.close()