设为首页 收藏本站
查看: 371|回复: 0

[经验分享] 使用Python将sql文件刷入DB

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-7-8 08:12:53 | 显示全部楼层 |阅读模式
Python学习第二弹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#coding = UTF-8

import os, sys, time, shutil

class NdbFlush:
    def __init__(self):
        self._ROOT_PATH_ = None
        self._TNS_LIST_ = {}
        self._FILE_LIST_ = {} # {SCHEMA:{'TAB':[], 'SEQ':[], 'PKGH':[]}, SCHEMA:{...}, ...}
        self._ORA_CFG_FILE_ = None
    def _UnInit_(self):
        self._ROOT_PATH_ = None
        self._TNS_LIST_ = None
        self._FILE_LIST_ = None
        self._ORA_CFG_FILE_ = None
         

    #######################################
    # 设置路径
    #######################################
    def GetFilePath(self):
        expath = os.getcwd()
        if os.path.isdir(expath):
            return expath
        elif os.path.isfile(expath):
            return os.path.dirname(expath)

    #######################################
    # 获取连接串列表
    #######################################
    def GetOraInfo(self):
        ora_file = self._ROOT_PATH_ + '/' + self._ORA_CFG_FILE_
        tns_list = {}
        fh = open(ora_file, 'r')
        for ora in fh.readlines():
            ora = ora.replace('\n', '')
            if ora and len(ora) > 5:
                ora_list = []
                schema = ora.split('/')[0].upper()
                ora_list = tns_list.get(schema)
                if (ora_list and len(ora_list) > 0):
                    ora_list.append(ora)
                else:
                    ora_list = [ora]
                tns_list[schema] = ora_list
        return tns_list

    #######################################
    # 将SQL文件名称加载到列表中
    #######################################
    def LoadNdbList(self, _list_):
        #print('[LoadNdbList] _list_ =', _list_, '\tlen(_list_)', len(_list_))
        lst = {}
        try:
            for itm in _list_:
                #print('\tITM =', itm)            
                file_split = itm.split('_')
                #print('\tfile_split[0] =', file_split[0], '\tfile_split[1] =', file_split[1])
                #schema = {}
                files = []
                schema = lst.get(file_split[1].upper())
                #print('\tschema =', schema)
                if schema and len(schema) > 0:
                    files = schema.get(file_split[0])
                    #print('\t\tfiles =', files)
                    if files and len(files) > 0:
                        files.append(itm)
                        schema[file_split[0]] = files
                        #print('\t\t\tfiles 1 =', files)
                        #print('\t\t\tschema =', schema)
                    else:
                        files = [itm]
                        schema[file_split[0]] = files
                        #print('\t\t\tfiles 2 =', files)
                else:
                    #print('\t', schema, file_split[0], itm)
                    schema = {}
                    files =[itm]
                    schema[file_split[0]] = files
                #print('\tschema =', schema)
                lst[file_split[1].upper()] = schema
                #print('\tLST =', lst)
                #print('-' * 80)
        except Exception as e:
            #print('请传入数组类参数(如:元组[])\n')
            print(e)
            lst = {}
        #print(lst)
        return lst

    #######################################
    # 获取SQL文件列表
    #######################################
    def GetSqlFileList(self):
        filelist = []
        sqlPath = self._ROOT_PATH_ + '/files/'
        for file in os.listdir(sqlPath):
            if file[-4:].upper() == '.SQL':
                if filelist:
                    filelist.append(file)
                else:
                    filelist = [file]
        #print('\n\n', filelist, '\n\n')
        print('在目录[' + sqlPath + ']下找到[%d]个SQL文件' % len(filelist))
        return filelist

    #######################################
    # 将SQL刷入DB
    #######################################
    def SqlFlushDB(self, _runMode_ = 'M'):
        # schema loop
        file_list = self._FILE_LIST_
        ora_list = self._TNS_LIST_
        filePath = self._ROOT_PATH_ + '/files/'
        for im in file_list:
            #print('schema =', im)#, lst.get(im))
                 
            # file type loop begin
            # SEQ
            for xm in file_list.get(im):
                #print('\ttype =', xm, '\n\tlist =', file_list.get(im).get(xm))
                if 'SEQ' == xm.upper():
                    self.InitBat(im, file_list, ora_list, filePath, xm, _runMode_)
            # TAB
            for xm in file_list.get(im):
                #print('\ttype =', xm, '\n\tlist =', file_list.get(im).get(xm))
                if 'TAB' == xm.upper():
                    self.InitBat(im, file_list, ora_list, filePath, xm, _runMode_)
            # TAB
            for xm in file_list.get(im):
                #print('\ttype =', xm, '\n\tlist =', file_list.get(im).get(xm))
                if 'PKGH' == xm.upper():
                    self.InitBat(im, file_list, ora_list, filePath, xm, _runMode_)
            # not in (TAB, SEQ)
            for xm in file_list.get(im):
                #print('\ttype =', xm, '\n\tlist =', file_list.get(im).get(xm))
                if 'TAB' != xm.upper() and 'SEQ' != xm.upper() and 'PKGH' != xm.upper():
                    self.InitBat(im, file_list, ora_list, filePath, xm, _runMode_)
            # file type loop end

    def InitBat(self, _schema_, _fileList_, _oraList_, _filePath_, _fileType_, _runMode_ = 'M'):
        # file name loop
        for file in _fileList_.get(_schema_).get(_fileType_):
            #print('\t\t', file)
            filePath = _filePath_
            sqlpath = filePath + file
            fh = open(sqlpath, 'a+')
            fh.write('\nexit')
            fh.close()

            tnslst = ''
            # ora conf loop
            fht = open(sqlpath + '.bat', 'a+')
            fht.write('title [' + file + ']\necho off\n')
            fht.write('cd ' + filePath + '\n')
            fht.write('cls\n\n\n')
            # tns loop
            for tns in _oraList_.get(_schema_):
                #print('\t\t\t', tns)
                tnslst += tns + ', '
                fht.write(('@echo "[ %s ]' %file) + (' -> [ %s]"' %tns) + '\n\n')
                fht.write('@echo 刷库中...\n\n')
                fht.write('sqlplus ' + tns + ' @' + file + ' >> ' + file + '.log\n\n\n')
                fht.flush()
            #fht.write('@pause\n')
            fht.write('@echo FINISH>' + file + '.ok')
            fht.write('\n\nexit')
            fht.close()
            print(('[ %s ]' %file) + (' -> [ %s]' %tnslst))
            if _runMode_ == 'M':
                self.RunBat(sqlpath, _runMode_)
            else:
                os.system(r'' + sqlpath + '.bat')
            #time.sleep(1)

            try:
                fhl = open(r'' + sqlpath + '.log', 'r')
                lines = fhl.readlines()
                lineidx = 0
                errFlag = False
                fhl.close()
                for line in lines:
                    lineU = line.upper()
                    if lineU.find('ERROR') >= 0:
                        errFlag = True
                        break
                    lineidx += 1
                if errFlag:
                    print('\t>>[Status] Failed..')
                    print('\t  [ ' + lines[lineidx].replace('\n', '') + ' ]')
                    print('\t  [ ' + lines[lineidx + 1].replace('\n', '') + ' ]')
                else:
                    print('\t>>[Status] Success..')
                    if os.path.isfile(r'' + sqlpath + '.log'):
                        os.remove(r'' + sqlpath + '.log')
                        shutil.move(sqlpath, sqlpath.replace('/files/', '/finish/'))
            except Exception as e:
                print('\t程序异常:', e)
                     
            print('-' * 70)


    def RunBat(self, _fileName_, _runMode_):
        state = 'START'
        while True:
        #print(runnext)
            if state == 'START':
                os.system('start ' + r'' + _fileName_ + '.bat')
                state = 'RUNNING'
                #print(1)
            elif state == 'FINISH':
                #print(9)
                break
            elif state == 'RUNNING':
                time.sleep(1)
                #print(2)
                try:
                    fh = open(r'' + _fileName_ + '.ok', 'r')
                    state = fh.read().replace('\n', '')
                except:
                    state = 'RUNNING'
            else:
                break
            
     
    def CleanFile(self, _mode_ = 'Finish'):
        tmpPath = self._ROOT_PATH_ + '/files/'
        for file in os.listdir(tmpPath):
            ffff = file.upper()
            delFlag = False
            if _mode_ == 'Finish':
                if ffff[-4:] == '.BAT' or ffff[-7:] == '.SQL.OK':
                    delFlag = True
            else:
                if ffff[-4:] == '.LOG' or ffff[-4:] == '.BAT' or ffff[-7:] == '.SQL.OK':
                    delFlag = True
            if delFlag:
                tmpFile = os.path.join(tmpPath,  file)
                if os.path.isfile(tmpFile):
                    os.remove(tmpFile)
            
    def Launcher(self):
            
        #l = ['tab_lpms_xxx.sql', 'tab_lpms_xx1x.sql', 'tab_lpms_xxxxx.sql', 'tab_wlt_xxx.sql', 'seq_lpms_xxx.sql', 'pkgh_jone_xxx.sql', 'pkgb_jone_xxx.sql', 'pubk_jone_xxx.sql']
        #self._FILE_LIST_ = self.LoadNdbList(l)
        # 清理历史bat文件

        self._ROOT_PATH_ = self.GetFilePath().replace('\\', '/')
        print('工作目录:', self._ROOT_PATH_)


        _clean_ = True
        _show_list_ = False
        _dosMode_ = 'M'
        #workp = 'D:/NdbFlush'
        ipt = input('>>')
        ipt = ipt.upper()
        if ipt == 'V':
            _show_list_ = True
        elif ipt == 'D1':
            _dosMode_ = 'S'
        elif ipt == 'D2':
            _dosMode_ = 'M'           
        elif ipt == 'Q':
            exit()
        elif ipt == 'C':
            _clean_ = True
        else:
            print('将以默认方式执行...')
        print('=' * 70)
        print('\n\n')
         
        self.CleanFile('Begin')

        self._FILE_LIST_ = self.LoadNdbList(self.GetSqlFileList())

        # 显示文件清单 BEGIN
        if _show_list_:
            lst = self._FILE_LIST_
            for im in lst:
                # schema
                print('schema =', im)#, lst.get(im))
                for xm in lst.get(im):
                    # file type
                    print('\ttype =', xm, '\n\tlist =', lst.get(im).get(xm))
        # 显示文件清单 END
         
        self._ORA_CFG_FILE_ = 'ora_tns_info.conf'
        self._TNS_LIST_ = self.GetOraInfo()        

        self.SqlFlushDB(_dosMode_)

        if _clean_:
            self.CleanFile()

        self._UnInit_()
        return self._FILE_LIST_, self._TNS_LIST_

        

def usage():
    print('=' * 70)
    print('=\t[ NDB 刷库工具 ] v1.0')
    print('=\t2015-07-05 by L')
    print('-' * 60)
    print('=\t[ Q: 退出; ]')
    print('=\t[ V: 显示录库的SQL列表; ]')
    print('=\t[ D1: 单窗口执行; D2:多窗口执行[默认]; ]')
    print('=\t[ \t执行前请确保: ')
    print('=\t \t\t1)SQL:[$WorkPath$/files/]')
    print('=\t \t\t2)TNS:[$WorkPath$/ora_tns_info.conf]')
    print('=\t[ 回车继续; ]')
    print('=' * 70)
     
if __name__ == '__main__':
    usage()
     
    ndb = NdbFlush()
    lst, ora = ndb.Launcher()

    print('\n\n')
    print('=' * 70)
    print('\n')
    print('刷库动作完毕,执行结果详见上面日志,失败信息已写入对应log文件$WorkPath$/file/*.log...\n[Enter]')
    input('')
     
   
    '''
    print('[MAIN] lst =', lst)
    print('[MAIN] ora =', ora)
    print('\n\n')
     
    print('\n\n\n\n')
    print('-' * 100)
    print('\n\n\n\n')
    for im in lst:
        # schema
        print('schema =', im)#, lst.get(im))
        for xm in lst.get(im):
            # file type
            print('\ttype =', xm, '\n\tlist =', lst.get(im).get(xm))
    '''



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-84261-1-1.html 上篇帖子: python中数组,元组,字典和字符串之间的转换 下篇帖子: python compile、eval、exec内建函数
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表