您的位置:首页 > 编程语言 > Python开发

python连接mysql

2015-07-23 19:09 555 查看

python如何连接mysql

主要使用了MySQLdb

代码部分

#!/usr/bin/python
# coding=utf-8
__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
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
#执行sql
cursor.execute(sql)

#获取sql执行完的结果(多条数据)
data = cursor.fetchall()

if len(data) > 0:
for fields in data:
#fields[0]一行数据的第一个字段
field1 = fields[0]
else:
break
print '执行完成,耗时(s):%d' % ((time.time() - startTime) / 1000)

except Exception:
print "处理时出现异常"
finally:
cursor.close()
conn.close()
file.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: