4353 发表于 2014-5-6 11:20:32

python 批量执行sql文件

需求: 要在服务器上指执行sql 为了不影响线上用户正常使用,且执行10000行暂停10秒。
然后用python 写了这样一个文件
文件存放位置: /root/sql/
文件名:2 3 4 5 6.....
这样做是为了省事 用 range(2,24)
其实可以写成读取目录文件:os.listdir("/root/sql/")

######## author shenym ###########
########2014-05-05   ###########
import os
import time
import math
##读取文件
for i in range(2,24):
   ##拼接文件完整路径
       filename="/root/sql/"+str(i)
       file= open(filename,'r')
       ##计数器(控制暂停)
       count=0
       for line in file:
               count +=1
               if line:
                     lines=line[:line.find(';')]
                     cmd="mysql -u root -pxxxx dbname -e "+'"'+lines+'"'
                     print cmd
                     os.system(cmd)
                     print count
                     if count == 10000:
                               time.sleep(10)
                               count=0
       file.close()


页: [1]
查看完整版本: python 批量执行sql文件