python连接mysql

来源:互联网 发布:正版matlab软件价格 编辑:程序博客网 时间:2024/06/10 10:53

python如何连接mysql

主要使用了MySQLdb

代码部分

#!/usr/bin/python# coding=utf-8__author__ = 'chunlongyuan'import MySQLdbimport urllib2import timehost = "localhost"user = "root"password = "root"db = "test_db"pageSize = 10try:    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 0
原创粉丝点击