python通过MySQLdb操作mysql

139 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

这里提供一个MySQLdb操作MYSQL数据库的例子。

在此之前首先需要知道的是MySQLdb仅仅支持到python 2.xx;另外MySQLdb的安装这里我们也不做介绍。

 

如下为一个使用实例。

#!/usr/bin/python
#-*-- coding:utf-8 -*--

import MySQLdb

#打开数据库连接
db = MySQLdb.connect(host='100.xx.xxx.233',port=1234, user='xxx_root',passwd='xxx_root@123',db='db_qiye_corp')

#使用cursor()方法获取操作游标 
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute('SELECT VERSION()')

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print "Database version : %s " % data

#开始for循环累加主号数
#for i in (69,70):
for i in range(0,100):
        table = 't_corp_basic_info_{0}'.format(i)
        sql = 'select count(*) from {0};'.format(table)
        print 'sql:{0}'.format(sql)
        cursor.execute(sql)
        data = cursor.fetchone()
        print "count of {0} is {1}".format(table, data)
        sum = sum + data[0]

print 'sum:{0}'.format(sum)

# 关闭数据库连接db.close()
db.close()