python中怎么利用cx_Oracle连接oracle数据库

发布时间:2021-07-29 14:39:25 作者:Leah
来源:亿速云 阅读:236

本篇文章为大家展示了python中怎么利用cx_Oracle连接oracle数据库,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

直接使用:
    CheckOracle.py -H [remote_home] -u [oracle_user] -p [oracle_password] -s [oracle_SID] -i [information] [table_name]
   具体使用细节和例子,使用-h获取帮助         
其他python调用:
    1 可以在实例化对象时指定参数
    2 调用的函数为OraInfo()
    3 返回结果集

  1. #!/usr/bin/env python3

  2. #_*_coding:utf-8_*_

  3. #Auth by raysuen

  4. #v1


  5. import cx_Oracle

  6. import sys,re,datetime



  7. class OracleConn(object): #封装类

  8.     #存放连接信息的

  9.     Info = {

  10.         "host":"127.0.0.1", #远端oracle的host

  11.         "port":1521, #远端oracle的port

  12.         "OraSID":None, #远端oracle的SID

  13.         "OraUser":None, #远端oracle的username

  14.         "OraPasswd":None, #远端oracle的username对应的密码

  15.         # "OraSchemas":None,

  16.         "OraInfo":None, #想要获取远端数据库的那种信息

  17.         "OraTable":None      #有关系的oracle的表名

  18.             }


  19.     def __init__(self,host=None,port=None,sid=None,orauser=None,orapwd=None,orainfo=None,oratable=None):

  20.         if host != None:

  21.             self.Info["host"] = host

  22.         if sid != None:

  23.             self.Info["OraSID"] = sid

  24.         if port != None:

  25.             self.Info["port"] = port

  26.         if orauser != None:

  27.             self.Info["OraUser"] = orauser

  28.         if orapwd != None:

  29.             self.Info["OraPasswd"] = orapwd

  30.         if orainfo != None:

  31.             self.Info["OraInfo"] = orainfo

  32.         if oratable != None:

  33.             self.Info["OraTable"] = oratable



  34.     def Check_Info(self): #判断Info字典里面的key是否存在必要的值

  35.         if self.Info["OraUser"] == None:

  36.             print("You must specify a oracle username for connecting oracle.")

  37.             print("If you don't know how to specify the parameters.You can -h to get help")

  38.             exit(3)

  39.         if self.Info["OraPasswd"] == None:

  40.             print("You must specify a oracle password for connecting oracle.")

  41.             print("If you don't know how to specify the parameters.You can -h to get help")

  42.             exit(3)

  43.         if self.Info["OraSID"] == None:

  44.             print("You must specify a oracle SID for connecting oracle.")

  45.             print("If you don't know how to specify the parameters.You can -h to get help")

  46.             exit(3)

  47.         if self.Info["OraInfo"] == None:

  48.             print("You must specify a Information about oracle")

  49.             print("If you don't know how to specify the parameters.You can -h to get help")

  50.             exit(3)


  51.     def ConnectOracle(self): #封装连接数据库的连接,并返回连接对象

  52.         try:

  53.             tnsname = cx_Oracle.makedsn(self.Info["host"], self.Info["port"], self.Info["OraSID"])

  54.             ora = cx_Oracle.connect(self.Info["OraUser"], self.Info["OraPasswd"], tnsname)

  55.         except Exception as e:

  56.             print(e)

  57.             exit(4)

  58.         return ora


  59.     def CloseOracle(self,oraCon): #封装管理数据库连接的函数

  60.         oraCon.close()


  61.     def ExecSql(self,SqlStr): #封装数据执行sql的函数

  62.         try:

  63.             ora = self.ConnectOracle()

  64.             cursor = ora.cursor()

  65.             cursor.execute(SqlStr)

  66.             res = cursor.fetchall()

  67.             cursor.close

  68.             self.CloseOracle(ora)

  69.         except Exception as e:

  70.             print(e)

  71.             exit(5)

  72.         return res



  73.     def GetTableSpace(self): #获取tablespace信息的函数

  74.         sqlStr="""

  75.               select  a.tablespace_name,

  76.                      round(a.bytes_alloc / 1024 / 1024, 2) megs_alloc,

  77.                      round(nvl(b.bytes_free, 0) / 1024 / 1024, 2) megs_free,

  78.                      round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024, 2) megs_used,

  79.                      round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100,2)||'%' Pct_Free,

  80.                      100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100,2)||'%' Pct_used,

  81.                      round(maxbytes/1048576,2) Max,

  82.                      round(round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024, 2) / round((case maxbytes when 0 then a.bytes_alloc else maxbytes end)/1048576,2) * 100,2) || '%' "USED_MAX%"

  83.               from  ( select  f.tablespace_name,

  84.                              sum(f.bytes) bytes_alloc,

  85.                              sum(decode(f.autoextensible, 'YES',f.maxbytes,'NO', f.bytes)) maxbytes

  86.                       from dba_data_files f

  87.                       group by tablespace_name) a,

  88.                     ( select  f.tablespace_name,

  89.                              sum(f.bytes)  bytes_free

  90.                       from dba_free_space f

  91.                       group by tablespace_name) b

  92.               where a.tablespace_name = b.tablespace_name (+)

  93.               union all

  94.               select h.tablespace_name,

  95.                      round(sum(h.bytes_free + h.bytes_used) / 1048576, 2) megs_alloc,

  96.                      round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576, 2) megs_free,

  97.                      round(sum(nvl(p.bytes_used, 0))/ 1048576, 2) megs_used,

  98.                      round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100,2)||'%' Pct_Free,

  99.                      100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100,2)||'%' pct_used,

  100.                      round(sum(f.maxbytes) / 1048576, 2) max,

  101.                      round(round(sum(nvl(p.bytes_used, 0))/ 1048576, 2)/round(sum(case f.maxbytes when 0 then (h.bytes_free + h.bytes_used) else f.maxbytes end) / 1048576, 2) * 100,2)||'%' "USED_MAX%"

  102.               from   sys.v_$TEMP_SPACE_HEADER h, sys.v_$Temp_extent_pool p, dba_temp_files f

  103.               where  p.file_id(+) = h.file_id

  104.               and    p.tablespace_name(+) = h.tablespace_name

  105.               and    f.file_id = h.file_id

  106.               and    f.tablespace_name = h.tablespace_name

  107.               group by h.tablespace_name

  108.               ORDER BY 1

  109.             """


  110.         res = self.ExecSql(sqlStr)

  111.         return res


  112.     def PrintTablespace(self,res):

  113.         headStr = """|%s|%s|%s|%s|%s|%s|%s|%s|"""%("tablespace_name".center(30),"megs_alloc".center(15),"megs_free".center(15),"megs_used".center(15),"Pct_Free".center(15),"Pct_used".center(15),"Max_MB".center(15),"USED_MAX_PCT".center(15))

  114.         print("%s"%"".center(144,"-"))

  115.         print(headStr)

  116.         print("%s" % "".center(144, "-"))

  117.         for t in res:

  118.             print("|%s|%s|%s|%s|%s|%s|%s|%s|"%(t[0].center(30),str(t[1]).center(15),str(t[2]).center(15),str(t[3]).center(15),t[4].center(15),t[5].center(15),str(t[6]).center(15),t[7].center(15)))

  119.         print("%s" % "".center(144, "-"))


  120.     def GetAsmDiskGroup(self):

  121.         sqlStr="""select name,total_mb,free_mb from v$asm_diskgroup"""

  122.         res = self.ExecSql(sqlStr)

  123.         return res


  124.     def PrintAsmDiskGroup(self,res):

  125.         print("%s" % "".center(50, "-"))

  126.         print("|%s|%s|%s|"%("GROUP_NAME".center(20),"TOTAL_MB".center(15),"FREE_MB".center(15)))

  127.         print("%s" % "".center(50, "-"))

  128.         for t in res:

  129.             print("|%s|%s|%s|"%(t[0].center(20),str(t[1]).center(15),str(t[2]).center(15)))

  130.         print("%s" % "".center(50, "-"))


  131.     def GetRedo(self):

  132.         sqlStr="""

  133.             select a.group#,a.BYTES/1024/1024 mb,b.MEMBER,a.thread#,a.sequence#,a.members,a.archived,a.status,a.first_time,a.next_time from gv$log a,gv$logfile b where a.GROUP#=b.GROUP# group by a.group#,a.thread#,a.BYTES/1024/1024,b.MEMBER,a.sequence#,a.members,a.archived,a.status,a.first_time,a.next_time order by group#

  134.             """

  135.         res = self.ExecSql(sqlStr)

  136.         return res


  137.     def PrintRedo(self,res):

  138.         print("%s" % "".center(148, "-"))

  139.         print("|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"%("GROUP".center(5),"SIZE_MB".center(7),"MEMBER".center(50),"THREAD".center(6),"SEQUENCE".center(8),"MEMBERS".center(7),"ARCHIVED".center(8),"STATUS".center(8),"FIRST_TIME".center(19),"NEXT_TIME".center(19)))

  140.         print("%s" % "".center(148, "-"))

  141.         for t in res:

  142.             if t[9] == None:

  143.                 tStr = "|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"%(str(t[0]).center(5),str(t[1]).center(7),t[2].center(50),str(t[3]).center(6),str(t[4]).center(8),str(t[5]).center(7),t[6].center(8),t[7].center(8),datetime.datetime.strftime(t[8],"%Y-%m-%d %H:%M:%S"),"None".center(19))

  144.             else:

  145.                 tStr = "|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|" % (

  146.                 str(t[0]).center(5), str(t[1]).center(7), t[2].center(50), str(t[3]).center(6), str(t[4]).center(8),

  147.                 str(t[5]).center(7), t[6].center(8), t[7].center(8),

  148.                 datetime.datetime.strftime(t[8], "%Y-%m-%d %H:%M:%S"),

  149.                 datetime.datetime.strftime(t[9], "%Y-%m-%d %H:%M:%S"))

  150.             print(tStr)

  151.         print("%s" % "".center(148, "-"))


  152.     def GetRedoShift(self):

  153.         sqlStr = """

  154.                   SELECT

  155.                   to_char(first_time,'YYYY-MM-DD') day,

  156.                   to_char(sum(decode(to_char(first_time,'HH24'),'00',1,0)),'999') "00",

  157.                   to_char(sum(decode(to_char(first_time,'HH24'),'01',1,0)),'999') "01",

  158.                   to_char(sum(decode(to_char(first_time,'HH24'),'02',1,0)),'999') "02",

  159.                   to_char(sum(decode(to_char(first_time,'HH24'),'03',1,0)),'999') "03",

  160.                   to_char(sum(decode(to_char(first_time,'HH24'),'04',1,0)),'999') "04",

  161.                   to_char(sum(decode(to_char(first_time,'HH24'),'05',1,0)),'999') "05",

  162.                   to_char(sum(decode(to_char(first_time,'HH24'),'06',1,0)),'999') "06",

  163.                   to_char(sum(decode(to_char(first_time,'HH24'),'07',1,0)),'999') "07",

  164.                   to_char(sum(decode(to_char(first_time,'HH24'),'08',1,0)),'999') "08",

  165.                   to_char(sum(decode(to_char(first_time,'HH24'),'09',1,0)),'999') "09",

  166.                   to_char(sum(decode(to_char(first_time,'HH24'),'10',1,0)),'999') "10",

  167.                   to_char(sum(decode(to_char(first_time,'HH24'),'11',1,0)),'999') "11",

  168.                   to_char(sum(decode(to_char(first_time,'HH24'),'12',1,0)),'999') "12",

  169.                   to_char(sum(decode(to_char(first_time,'HH24'),'13',1,0)),'999') "13",

  170.                   to_char(sum(decode(to_char(first_time,'HH24'),'14',1,0)),'999') "14",

  171.                   to_char(sum(decode(to_char(first_time,'HH24'),'15',1,0)),'999') "15",

  172.                   to_char(sum(decode(to_char(first_time,'HH24'),'16',1,0)),'999') "16",

  173.                   to_char(sum(decode(to_char(first_time,'HH24'),'17',1,0)),'999') "17",

  174.                   to_char(sum(decode(to_char(first_time,'HH24'),'18',1,0)),'999') "18",

  175.                   to_char(sum(decode(to_char(first_time,'HH24'),'19',1,0)),'999') "19",

  176.                   to_char(sum(decode(to_char(first_time,'HH24'),'20',1,0)),'999') "20",

  177.                   to_char(sum(decode(to_char(first_time,'HH24'),'21',1,0)),'999') "21",

  178.                   to_char(sum(decode(to_char(first_time,'HH24'),'22',1,0)),'999') "22",

  179.                   to_char(sum(decode(to_char(first_time,'HH24'),'23',1,0)),'999') "23"

  180.                   from

  181.                   v$log_history

  182.                   GROUP by

  183.                   to_char(first_time,'YYYY-MM-DD') order by day desc

  184.                  """

  185.         res = self.ExecSql(sqlStr)

  186.         return res


  187.     def PrintRedoShift(self,res):

  188.         print("%s" % "".center(132, "-"))

  189.         print("|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"%("DAY".center(10),"00".center(4),"01".center(4),"02".center(4),"03".center(4),"04".center(4),"05".center(4),"06".center(4),"07".center(4),"08".center(4),"09".center(4),"10".center(4),"11".center(4),"12".center(4),"13".center(4),"14".center(4),"15".center(4),"16".center(4),"17".center(4),"18".center(4),"19".center(4),"20".center(4),"21".center(4),"22".center(4),"23".center(4)))

  190.         print("%s" % "".center(132, "-"))

  191.         for t in res:

  192.             print("|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"%(t[0].center(10),t[1].center(4),t[2].center(4),t[3].center(4),t[4].center(4),t[5].center(4),t[6].center(4),t[7].center(4),t[8].center(4),t[9].center(4),t[10].center(4),t[11].center(4),t[12].center(4),t[12].center(4),t[13].center(4),t[14].center(4),t[15].center(4),t[16].center(4),t[17].center(4),t[18].center(4),t[19].center(4),t[20].center(4),t[21].center(4),t[22].center(4),t[23].center(4)))

  193.         print("%s" % "".center(132, "-"))



  194.     def GetExecNow(self):

  195.         sqlStr = """

  196.                 select distinct b.SID,b.SERIAL#,p.SPID,b.LAST_CALL_ET,a.sql_id, a.sql_text,b.status,b.event,b.MODULE, b.OSUSER,b.MACHINE from v$sql a,v$session b,v$process p where a.SQL_ID=b.SQL_ID and b.PADDR=p.ADDR and b.STATUS='ACTIVE' order by B.LAST_CALL_ET desc

  197.                 """

  198.         res = self.ExecSql(sqlStr)

  199.         return res


  200.     def PrintExecNow(self,res):

  201.         print("%s" % "".center(188, "-"))

  202.         print("|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"%("SID".center(6),"SERIAL".center(6),"SPID".center(5),"LAST_ET".center(7),"SQL_ID".center(15),"SQL_TEXT".center(60),"STATUS".center(7),"EVENT".center(30),"MODULE".center(15),"OSUSER".center(10),"MACHINE".center(15)))

  203.         print("%s" % "".center(188, "-"))

  204.         for t in res:

  205.             print("|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"%(str(t[0]).center(6),str(t[1]).center(6),t[2].center(5),str(t[3]).center(7),t[4].center(15),t[5].strip()[0:60].center(60),t[6].center(7),t[7][0:30].center(30),t[8][0:15].center(15),t[9].center(10),t[10][0:15].center(15)))

  206.         print("%s" % "".center(188, "-"))



  207.     def GetIndexInfo(self):

  208.         if self.Info["OraTable"] == None:

  209.             print("You must specify a oracle table to get indexs information of table.")

  210.             print("If you don't know how to specify the parameters.You can -h to get help")

  211.             exit(6)

  212.         sqlStr = """

  213.                 select

  214.                     table_name,

  215.                     TABLE_TYPE,

  216.                     INDEX_NAME,

  217.                     INDEX_TYPE,

  218.                     TABLE_OWNER,

  219.                     max(columns) columns

  220.                 from

  221.                 (SELECT

  222.                     ui.table_name,

  223.                     ui.TABLE_TYPE,

  224.                     ui.INDEX_NAME,

  225.                     ui.INDEX_TYPE,

  226.                     uic.TABLE_OWNER,

  227.                     to_char(wm_concat (uic.COLUMN_NAME)

  228.                         over(partition by ui.table_name,ui.TABLE_TYPE,ui.INDEX_NAME,ui.INDEX_TYPE,uic.TABLE_OWNER order by uic.COLUMN_POSITION)) columns

  229.                 FROM

  230.                     dba_indexes ui,

  231.                     dba_IND_COLUMNS uic

  232.                 WHERE

  233.                     ui.INDEX_NAME (+) = uic.INDEX_NAME

  234.                 AND ui.TABLE_NAME = UPPER ('%s'))

  235.                 GROUP BY

  236.                     table_name,

  237.                     TABLE_TYPE,

  238.                     INDEX_NAME,

  239.                     INDEX_TYPE,

  240.                     TABLE_OWNER

  241.                 """%self.Info["OraTable"]

  242.         res = self.ExecSql(sqlStr)

  243.         return res



  244.     def PrintIndexInfo(self,res):

  245.         print("%s" % "".center(142, "-"))

  246.         print("|%s|%s|%s|%s|%s|%s|"%("TABLE_NAME".center(20),"TABLE_TYPE".center(20),"INDEX_NAME".center(25),"INDEX_TYPE".center(15),"TABLE_OWNER".center(15),"COLUMNS".center(40)))

  247.         print("%s" % "".center(142, "-"))

  248.         for t in res:

  249.             print("|%s|%s|%s|%s|%s|%s|" % (t[0].center(20), t[1].center(20), t[2].center(25), t[3].center(15), t[4].center(15), t[5].center(40)))


  250.         print("%s" % "".center(142, "-"))



  251.     def GetPartInfo(self):

  252.         if self.Info["OraTable"] == None:

  253.             print("You must specify a oracle table to get indexs information of table.")

  254.             print("If you don't know how to specify the parameters.You can -h to get help")

  255.             exit(6)

  256.         sqlStr = """

  257.                 SELECT

  258.                     a.TABLE_OWNER,

  259.                     a.table_name,

  260.                     c. M,

  261.                     a.PARTITION_NAME,

  262.                     a.HIGH_VALUE,

  263.                     a.NUM_ROWS,

  264.                     a.TABLESPACE_NAME,

  265.                     b.COLUMN_NAME,

  266.                     A .LAST_ANALYZED

  267.                 FROM

  268.                     dba_TAB_PARTITIONS A,

  269.                     DBA_PART_KEY_COLUMNS b,

  270.                     (

  271.                         SELECT

  272.                             SUM (bytes / 1024 / 1024) M,

  273.                             segment_name,

  274.                             partition_name

  275.                         FROM

  276.                             dba_segments

  277.                         WHERE segment_type LIKE '%%TABLE%%'

  278.                         AND partition_name IS NOT NULL

  279.                         and segment_name = upper('%s')

  280.                         GROUP BY

  281.                             segment_name,

  282.                             partition_name

  283.                         ORDER BY

  284.                             segment_name,

  285.                             partition_name DESC

  286.                     ) c

  287.                 WHERE

  288.                     A .TABLE_NAME = b. NAME (+)

  289.                 AND A .table_name = c.SEGMENT_NAME

  290.                 AND A .partition_name = c.PARTITION_NAME

  291.                 AND A .table_name = upper('%s')

  292.                 ORDER BY

  293.                     A .TABLE_NAME,

  294.                     partition_name DESC

  295.                 """%(self.Info["OraTable"],self.Info["OraTable"])

  296.         res = self.ExecSql(sqlStr)

  297.         return res


  298.     def PrintPartInfo(self,res):

  299.         print("%s" % "".center(184, "-"))

  300.         print("|%s|" % "TABLE_OWNER".center(15), end='')

  301.         print("%s|" % "TABLE_NAME".center(25), end='')

  302.         print("%s|" % "MB".center(5), end='')

  303.         print("%s|" % "PARTITION_NAME".center(20), end='')

  304.         print("%s|" % "HIGH_VALUE".center(40), end='')

  305.         print("%s|" % "NUM_ROWS".center(10), end='')

  306.         print("%s|" % "TABLESPACE".center(20), end='')

  307.         print("%s|" % "CULUMN_NAME".center(20), end='')

  308.         print("%s|" % "LAST_ANALYZED".center(19))

  309.         print("%s" % "".center(184, "-"))


  310.         for t in res:

  311.             print("|%s|"%t[0].center(15),end='')

  312.             print("%s|"%t[1].center(25), end='')

  313.             print("%s|"%str(t[2]).center(5), end='')

  314.             print("%s|"%t[3].center(20), end='')

  315.             print("%s|"%t[4][0:40].center(40), end='')

  316.             print("%s|"%str(t[5]).center(10), end='')

  317.             print("%s|"%t[6].center(20), end='')

  318.             if t[7] == None:

  319.                 print("%s|"%"None".center(20))

  320.             else:

  321.                 print("%s|"%t[7].center(20), end='')

  322.             print("%s|"%(datetime.datetime.strftime(t[8],"%Y-%m-%d %H:%M:%S")))

  323.         print("%s" % "".center(184, "-"))


  324.     def OraInfo(self): #这个函数不格式化打印返回结果,只返回结果集

  325.         self.Check_Info()

  326.         if self.Info["OraInfo"].upper() == "TABLESPACE":

  327.             self.GetTableSpace()

  328.         elif self.Info["OraInfo"].upper() == "ASMDISKGROUP":

  329.             self.GetAsmDiskGroup()

  330.         elif self.Info["OraInfo"].upper() == "REDO":

  331.             self.GetRedo()

  332.         elif self.Info["OraInfo"].upper() == "REDOSHIFT":

  333.             self.GetRedoShift()

  334.         elif self.Info["OraInfo"].upper() == "EXECNOW":

  335.             self.GetExecNow()

  336.         elif self.Info["OraInfo"].upper() == "INDEXINFO":

  337.             self.GetIndexInfo()

  338.         elif self.Info["OraInfo"].upper() == "PARTITIONINFO":

  339.             self.GetPartInfo()

  340.         else:

  341.             print("Please enter valid value for -i")

  342.             exit(6)



  343.     def PrintOraInfo(self):

  344.         self.Check_Info()

  345.         if self.Info["OraInfo"].upper() == "TABLESPACE":

  346.             self.PrintTablespace(self.GetTableSpace())

  347.         elif self.Info["OraInfo"].upper() == "ASMDISKGROUP":

  348.             self.PrintAsmDiskGroup(self.GetAsmDiskGroup())

  349.         elif self.Info["OraInfo"].upper() == "REDO":

  350.             self.PrintRedo(self.GetRedo())

  351.         elif self.Info["OraInfo"].upper() == "REDOSHIFT":

  352.             self.PrintRedoShift(self.GetRedoShift())

  353.         elif self.Info["OraInfo"].upper() == "EXECNOW":

  354.             self.PrintExecNow(self.GetExecNow())

  355.         elif self.Info["OraInfo"].upper() == "INDEXINFO":

  356.             self.PrintIndexInfo(self.GetIndexInfo())

  357.         elif self.Info["OraInfo"].upper() == "PARTITIONINFO":

  358.             self.PrintPartInfo(self.GetPartInfo())

  359.         else:

  360.             print("Please enter valid value for -i")

  361.             exit(6)


  362. def fun_help():

  363.     helpStr = """

  364.     Name

  365.         CheckOracle.py      display information which you want to know

  366.     

  367.     Synopsis

  368.         CheckOracle.py -H [romote_host] -u [oracle user] -p [oracle password] -s [oracle SID] -i [information] [table_name]

  369.     

  370.     Description

  371.         -H Specify a remote host,defaul 127.0.0.1.

  372.         -u Specify a oracle user

  373.         -p Specify a oracle password

  374.         -s Specify a oracle SID

  375.         -i Specify a action information what you want to know

  376.             Value:

  377.                 tablespace

  378.                 asmdiskgroup

  379.                 redo

  380.                 redoshift

  381.                 execnow

  382.                 indexinfo

  383.                     Table_name must be specified after indexinfo.

  384.                 partitioninfo

  385.                     Table_name must be specified after partitioninfo.

  386.     

  387.     Example

  388.         python3 CheckOracle.py -H 127.0.0.1 -u system -p BIIpass01 -s masdb3 -i execnow

  389.         python3 CheckOracle.py -H 127.0.0.1 -u system -p BIIpass01 -s masdb3 -i indexinfo dept

  390.         python3 CheckOracle.py -H 127.0.0.1 -u system -p BIIpass01 -s masdb3 -i partitioninfo dept

  391.     """

  392.     print(helpStr)


  393. if __name__=="__main__":

  394.     # print(sys.argv)

  395.     # print(len(sys.argv))


  396.     if len(sys.argv) > 1: #判断是否传递了参数

  397.         for i in range(1,len(sys.argv)): #循环参数下标

  398.             # print(sys.argv[i])

  399.             if sys.argv[i] == "-H": #判断参数

  400.                 if re.match("^-",sys.argv[i+1]) == None: #判断当先的下一个参数是否为-开头,-开头不是正取的value值

  401.                     i += 1   #下标加1

  402.                     OracleConn.Info["host"] = sys.argv[i] #获取参数值

  403.                 else:

  404.                     print("-H.You use this parameter,but no value are specified") #当前参数的下一个参数,不是正取的value值,报错退出

  405.                     exit(2)

  406.             elif sys.argv[i] == "-u":

  407.                 if re.match("^-", sys.argv[i+1]) == None:

  408.                     i += 1

  409.                     OracleConn.Info["OraUser"] = sys.argv[i]

  410.                 else:

  411.                     print("-u.You use this parameter,but no value are specified")

  412.                     exit(2)

  413.             elif sys.argv[i] == "-p":

  414.                 if re.match("^-", sys.argv[i+1]) == None:

  415.                     i += 1

  416.                     OracleConn.Info["OraPasswd"] = sys.argv[i]

  417.                 else:

  418.                     print("-p.You use this parameter,but no value are specified")

  419.                     exit(2)

  420.             elif sys.argv[i] == "-P":

  421.                 if re.match("^-", sys.argv[i+1]) == None:

  422.                     i += 1

  423.                     OracleConn.Info["port"] = sys.argv[i]

  424.                 else:

  425.                     print("-P.You use this parameter,but no value are specified")

  426.                     exit(2)

  427.             elif sys.argv[i] == "-S":

  428.                 if re.match("^-", sys.argv[i+1]) == None:

  429.                     i += 1

  430.                     OracleConn.Info["OraSchemas"] = sys.argv[i].upper()

  431.                 else:

  432.                     print("-S.You use this parameter,but no value are specified")

  433.                     exit(2)

  434.             elif sys.argv[i] == "-s":

  435.                 if re.match("^-", sys.argv[i+1]) == None:

  436.                     i += 1

  437.                     OracleConn.Info["OraSID"] = sys.argv[i]

  438.                 else:

  439.                     print("-S.You use this parameter,but no value are specified")

  440.                     exit(2)

  441.             elif sys.argv[i] == "-i":

  442.                 if re.match("^-", sys.argv[i+1]) == None:

  443.                     i += 1

  444.                     OracleConn.Info["OraInfo"] = sys.argv[i]

  445.                     if i+1 < len(sys.argv) and re.match("^-", sys.argv[i+1]) == None:

  446.                         i += 1

  447.                         OracleConn.Info["OraTable"] = sys.argv[i]

  448.                 else:

  449.                     print("-s.You use this parameter,but no value are specified")

  450.                     exit(2)

  451.             elif sys.argv[i] == "-h":

  452.                 fun_help()

  453.                 exit(0)

  454.     else:

  455.         print("Please enter right parameters")

  456.         exit(1)

  457.     oc = OracleConn() #实例化类对象

  458.     oc.PrintOraInfo() #调用类的接口函数,打印结果

上述内容就是python中怎么利用cx_Oracle连接oracle数据库,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. python 安装 cx_Oracle
  2. python   install cx_Oracle

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python cx_oracle oracle

上一篇:XamarinEssentials中怎么获取首选项的值

下一篇:vbs中如何获取Am注册路径信息

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》