#!/usr/bin/env pythonimport mysqlfrom mysql import connectorimport timeimport osdef dowork(): sql_db=("show databases") cursora=conn.cursor() cursora.execute(sql_db) cursorb=conn.cursor() dbs=[] for db in cursora: conn.database=db cursorb.execute("show tables") for table in cursorb: if 'goods_moves' in table: dbs.append(db) cursora.close() cursorb.close() return dbs#把文件中的sql语句存入字典中,然后每个数据库顺序执行def get_sql(): fp=file("update.sql",'r') sql={} count=1 str_sql=str() for line in fp.readlines(): if line.strip().startswith('/*'):continue if line.strip().endswith(";"): sql[count]=str_sql+line str_sql='' count=count+1 else: str_sql=str_sql+line fp.close() return sqldef modify_table(dbs,sql): cursora=conn.cursor() for db in dbs: conn.database=db try: for k,v in sql.iteritems(): cursora.execute(v) except Exception: bad.append(db[0]) else: print db[0],time.strftime("%k:%M:%S") conn.commit() cursora.close()def writeDbToFile(dbs,output): dbfile=file(output,'w') for db in dbs: dbfile.write(db[0]+os.linesep) dbfile.flush() dbfile.close()def checkSql(sql): for k,v in sql.iteritems(): print k,vif __name__ == '__main__': config={ 'user':"root", 'password':'1234456', 'host':'192.168.10.1', 'port':13306, 'buffered':True } bad=[] err=file("error.log",'w') conn=mysql.connector.connect(**config) dbs=dowork() writeDbToFile(dbs,config["host"]+".dbs.txt") sql=get_sql() #checkSql(sql) modify_table(dbs,sql) err.write(os.linesep.join(bad)) err.close() conn.close()