标签:turn ble str strip sel 内容 sql add password
最近需要用Python连接Oracle操作,之前接触过,没自己手写过,特此记录。数据库是Oracle 11,python版本2.7的。
这个需求是两个库A和B,假设现在需要识别一张表在A库里面有没记录,如果没有,将表名写入一个log,如果有再去B库里查有没有该表,如果没有,表名计入另外一个log文件。
select t.* from all_objects t where t.object_name = upper(&table_name);
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import cx_Oracle 5 6 #username 7 dbusernamea = ‘username1‘ 8 dbusernameb = ‘username2‘ 9 10 #dbconnectaddress 11 db_usernamea = cx_Oracle.connect(dbusernamea,‘password‘,‘dbaddress‘) 12 db_usernameb = cx_Oracle.connect(dbusernameb,‘password‘,‘dbaddress‘) 13 14 #cursor 15 cur_usernamea = db_usernamea.cursor() 16 cur_usernameb = db_usernameb.cursor() 17 18 #readtablename 19 def ReadTableName(): 20 fo = open("tablename.txt","r"): 21 print(‘open success!‘) 22 table_name = [] 23 for i in fo.readlines(): 24 if i != ‘\n‘ and i != ‘\r\n‘: 25 spiliti = i.replace(‘\t‘,‘‘).strip() 26 table_name.append(spiliti) 27 fo.close() 28 return table_name 29 30 # 31 def CheckMainTable(ReadTableName): 32 33 for tablename in ReadTableName: 34 sql_str_checkmaintable = """select a.* from all_objects a where a.object_name = upper(%s) """%tablename 35 cur_usernamrea.execute(sql_str_checkmaintable) 36 #获取结果集 37 rets = cur_usernamea.fetchall() 38 #如果结果集为空判断该表在A中不存在 39 if length(rets) == 0: 40 print(‘MainAcess don‘t have this table: ‘+tablename+‘\n‘) 41 #写入log writelines即可 如有需要 42 with open("filename_a","a") as a: 43 a.writelines.(tablename+‘\n‘) 44 45 else: 46 sql_str_checksubtable = """select a.* from all_objects a where a.object_name = upper(%s) """%tablename 47 cur_usernamreb.execute(sql_str_checksubtable) 48 #获取结果集 49 recv = cur_usernameb.fetchall() 50 #如果结果集为空判断该表在B中不存在 51 if length(recv) == 0: 52 print(‘SubAcess don‘t have this table: ‘+tablename+‘\n‘) 53 #写入log writelines即可 如有需要 54 with open("filename_b","a") as b: 55 b.writelines.(tablename+‘\n‘) 56 57 if __name__ == ‘__main__‘: 58 CheckMainTable(ReadTableName()) 59 60 #关闭游标 61 db_usernamea.close() 62 db_usernameb.close()
其实最近也是才开始学习Python连接数据库这个东西,里面一些内容可能写的不好,也不是很完善。因为是纯粹手打,代码可能会有疏漏,有错误的地方如果有人看见请指出,我会及时修正。这个脚本在工作中运行过,亲测有效。但是其实里面有部分内容我也是搜索的,了解的不具体,复制过来改改就用了,所以有问题请大家不吝赐教。
标签:turn ble str strip sel 内容 sql add password
原文地址:https://www.cnblogs.com/littlegao-world/p/12422835.html