python连接mysql
python如何连接mysql主要使用了MySQLdb代码部分#!/usr/bin/python# coding=utf-8__author__ = 'chunlongyuan'import MySQLdbimport urllib2import timehost = "localhost"user = "root"password = "root"db = "test_db"page
·
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()
更多推荐



所有评论(0)