python频繁连接mysql_python批量连接mysql

这个脚本(gomysql.py)用于批量连接多个MySQL数据库,根据输入的dbip.ini配置文件和sql语句文本执行操作。用户需要确认输入信息后,脚本将依次连接每个数据库执行SQL并打印结果。
摘要由CSDN通过智能技术生成

注释:脚本(gomysql.py)需要进一步优化,初学者,努力中

首先配置需要执行的dbip.ini列表,格式如下

S1  192.168.0.5   3306  dbusername dbpasswd dbname

S2  192.168.0.6   3306 dbusername dbpasswd  dbname

S3  192.168.0.7   3306 dbusername dbpasswd  dbname

执行方法:./gomysql.py dbip.ini(参数一,数据库账号IP配置列表,实例如下) db.sql(参数二,执行的sql语句文本)

效果:

# ./readlnedb.py logdbip.ini 20150827/select_22.sql

logdbip.ini

20150827/select_22.sql

确认以上信息[y/n]:

脚本内容如下:

#!/usr/bin/python

#encoding:utf-8

import sys

import os

import MySQLdb

import datetime

if len(sys.argv) < 2:

print "error: " + sys.argv[0] + "file1 file2"

sys.exit()

file1=sys.argv[1]

file2=sys.argv[2]

print file1

print file2

#sql = open(file2,"r").read()

#print sql

str = raw_input("确认以上信息[y/n]:")

if str != "y":

exit()

for line in open(file1,"r"):

servername=line.strip().split()[0]

ip=line.strip().split()[1]

port=line.strip().split()[2]

user=line.strip().split()[3]

pswd=line.strip().split()[4]

dbname=line.strip().split()[5]

print "\n=======",servername,"==========="

db = MySQLdb.connect(ip,user,pswd,dbname)

cursor = db.cursor()

for sql in open(file2,"r"):

cursor.execute(sql)

data = cursor.fetchall()

for row in data:

print "\n"

num = 0

while (num < len(row)):

print row[num],

num += 1

db.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值