我的编程空间,编程开发者的网络收藏夹
学习永远不晚

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

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

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

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

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

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

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

下载Word文档

猜你喜欢

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

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

如何利用Python连接Oracle数据库

这篇“如何利用Python连接Oracle数据库”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“如何利用Python连接Ora
2023-07-02

ORACLE中CX_ORACLE库怎么用

小编给大家分享一下ORACLE中CX_ORACLE库怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!1、安装cx_Oracle包:pip install cx
2023-06-02

python怎么连接oracle数据库

使用Python连接Oracle数据库使用Python连接Oracle数据库需要安装cx_Oracle模块和Oracle客户机。步骤包括导入模块、创建连接、创建游标、执行查询、获取结果、处理结果和关闭连接。示例代码展示了连接数据库并执行查询的完整流程。提示包括确保连接信息正确,使用匹配的cx_Oracle版本,并在开发前查阅cx_Oracle文档。
python怎么连接oracle数据库
2024-04-13

python怎么连接oracle数据库

要连接Oracle数据库,首先需要安装Oracle客户端,并且安装cx_Oracle模块。然后可以使用以下Python代码连接Oracle数据库:import cx_Oracle# 连接数据库conn = cx_Oracle.conne
python怎么连接oracle数据库
2024-04-09

Python 连接 Oracle数据库

1.环境设置[root@oracle ~]# cat /etc/redhat-release CentOS release 6.9 (Final)[root@oracle ~]# python -VPython 2.6.6版本:Oracle
2023-01-31

linux中怎么利用python3连接mysql数据库

linux中怎么利用python3连接mysql数据库,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。1.安装pymysqlpymysql就是作为python3环境下mysq
2023-06-09

C#中怎么连接Oracle数据库

本篇文章为大家展示了C#中怎么连接Oracle数据库,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。C#连接Oracle数据库字符串(查询数据)using System; using System.
2023-06-17

java中怎么连接oracle数据库

使用JDBC连接Oracle数据库的步骤:添加OracleJDBC驱动程序并加载驱动程序。使用DriverManager建立数据库连接。使用Statement或PreparedStatement对象执行SQL语句。使用ResultSet对象处理查询结果。关闭连接以释放资源。高级特性包括连接池、事务、游标和调用存储过程/函数。示例代码演示如何连接到数据库、执行查询并处理结果集。
java中怎么连接oracle数据库
2024-04-12

java中怎么连接oracle数据库

在Java中连接Oracle数据库主要有两种方式:使用JDBC驱动和使用第三方框架(如MyBatis、Hibernate等)。1、使用JDBC驱动连接Oracle数据库:首先需要下载Oracle官方提供的JDBC驱动(ojdbc.jar)
java中怎么连接oracle数据库
2024-03-11

oracle怎么连接数据库

如何使用 oracle 连接数据库第一步:获取连接信息要连接到 Oracle 数据库,你需要以下信息:主机名或 IP 地址端口号(默认为 1521)服务名或 SID用户名密码第二步:使用 SQL*Net 连接Windows:打
oracle怎么连接数据库
2024-05-30

oracle怎么用dblink连接数据库

在Oracle数据库中,使用数据库链接(DBLink)连接到另一个数据库的语法如下:创建数据库链接:CREATE DATABASE LINK dblink_nameCONNECT TO username IDENTIFIED BY pas
oracle怎么用dblink连接数据库
2024-04-09

利用java怎么对oracle或mysql数据库进行连接

这篇文章给大家介绍利用java怎么对oracle或mysql数据库进行连接,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。具体方法如下:package com.nuo.test.Connection;import jav
2023-05-31

Python中怎么连接PostgreSQL数据库

今天就跟大家聊聊有关Python中怎么连接PostgreSQL数据库,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。1. 安装PostgreSQL数据库,数据库的下载用的可以用8.4.
2023-06-17

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录