iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python中怎么利用cx_Oracle连接oracle数据库
  • 734
分享到

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

2023-06-04 10:06:05 734人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

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

本篇文章为大家展示了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数据库,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注编程网Python频道。

--结束END--

本文标题: python中怎么利用cx_Oracle连接oracle数据库

本文链接: https://www.lsjlt.com/news/237352.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python中怎么利用cx_Oracle连接oracle数据库
    本篇文章为大家展示了python中怎么利用cx_Oracle连接oracle数据库,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。直接使用:    CheckOracle.py -...
    99+
    2023-06-04
  • 如何利用Python连接Oracle数据库
    这篇“如何利用Python连接Oracle数据库”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“如何利用Python连接Ora...
    99+
    2023-07-02
  • ORACLE中CX_ORACLE库怎么用
    小编给大家分享一下ORACLE中CX_ORACLE库怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!安装cx_Oracle包:pip install cx_O...
    99+
    2023-06-02
  • python怎么连接oracle数据库
    要连接Oracle数据库,首先需要安装Oracle客户端,并且安装cx_Oracle模块。然后可以使用以下Python代码连接Ora...
    99+
    2024-04-09
    python oracle
  • 数据库中cx_oracle怎么用使用
    这篇文章给大家分享的是有关数据库中cx_oracle怎么用使用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。 连接 import cx_Oracle ...
    99+
    2024-04-02
  • Python 连接 Oracle数据库
    1.环境设置[root@oracle ~]# cat /etc/redhat-release CentOS release 6.9 (Final)[root@oracle ~]# python -VPython 2.6.6版本:Oracle...
    99+
    2023-01-31
    数据库 Python Oracle
  • python--连接oracle数据库
    python--连接oracle数据库 前言一、安装cx_Oracle二、导入库三、数据库操作实例3.1 连接3.2数据库查询3.3数据库插入3.4 实例从某网站上面爬取彩票号码 四、异常...
    99+
    2023-09-07
    数据库 python oracle
  • C#中怎么连接Oracle数据库
    本篇文章为大家展示了C#中怎么连接Oracle数据库,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。C#连接Oracle数据库字符串(查询数据)using System; &nbs...
    99+
    2023-06-17
  • java中怎么连接oracle数据库
    在Java中连接Oracle数据库主要有两种方式:使用JDBC驱动和使用第三方框架(如MyBatis、Hibernate等)。 1、...
    99+
    2024-03-11
    java oracle
  • linux中怎么利用python3连接mysql数据库
    linux中怎么利用python3连接mysql数据库,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。1.安装pymysqlpymysql就是作为python3环境下mysq...
    99+
    2023-06-09
  • Python中如何连接oracle数据库
    这篇文章给大家介绍Python中如何连接oracle数据库,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。1. 基本连接–使用Oracle tns aliasconnection=cx_...
    99+
    2024-04-02
  • oracle怎么用dblink连接数据库
    在Oracle数据库中,使用数据库链接(DBLink)连接到另一个数据库的语法如下: 创建数据库链接: CREATE DATAB...
    99+
    2024-04-09
    oracle 数据库
  • 利用java怎么对oracle或mysql数据库进行连接
    这篇文章给大家介绍利用java怎么对oracle或mysql数据库进行连接,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。具体方法如下:package com.nuo.test.Connection;import jav...
    99+
    2023-05-31
    java oracle mysql
  • Oracle中怎么修改数据库连接数
    这期内容当中小编将会给大家带来有关Oracle中怎么修改数据库连接数,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。windows系统 Oracle 数据库连接数的修改&n...
    99+
    2024-04-02
  • Java中怎么利用JDBC实现数据库连接
    Java中怎么利用JDBC实现数据库连接,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。 JDBC:...
    99+
    2024-04-02
  • SQL中怎么连接Oracle数据库可
    这篇文章给大家介绍SQL中怎么连接Oracle数据库可,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。一、ORA-12514:TNS:监听程序当前无法识别连接描述符中请求的服务。cd $...
    99+
    2024-04-02
  • 怎么在plsql中连接oracle数据库
    这篇文章将为大家详细讲解有关怎么在plsql中连接oracle数据库,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。第一步:先安装plsql客户端,plsql...
    99+
    2024-04-02
  • Python中怎么连接PostgreSQL数据库
    今天就跟大家聊聊有关Python中怎么连接PostgreSQL数据库,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。 安装PostgreSQL数据库,数据库的下载用的可以用8.4.2版...
    99+
    2023-06-17
  • python怎么连接数据库_python连接数据库教程
    1、首先python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库:。 2、然后可以访问Python数据库接口及API查看详细的支持数据库列表。不同的数据库你需要下载不同...
    99+
    2024-04-02
  • 怎么在Oracle中使用sqlplus连接数据库
    怎么在Oracle中使用sqlplus连接数据库?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。方式1(本机): / as sysdba在ora...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作