获取Oracle表的分析时间

上节讲到如何建立一个Oracle命令的界面,并显示数据库文件的创建时间

这节讲如何查看指定表的分析时间

我们在日常SQL优化的过程中,肯定要知道表的统计信息是否正确,而这个功能的话就能简化这个操作

注意:不支持索引的分析时间,多个表查询请使用空格隔开

开发环境

操作系统:CentOS 7.3

Python版本 :2.7

Django版本: 1.10.5

操作系统用户:oracle

建立页面的步骤

我们还是通过这张图的步骤来说明如何建立页面

Alt text

urls.py页面

首先是monitor/urls.py,这节不需要修改这个文件

urlpatterns = [
   url(r'^$', views.index, name='index'),
   url(r'^oracle_command/$',views.oracle_command, name='oracle_command'),
   url(r'^commandresult/$',views.commandresult, name='commandresult'),
]

oracle_command为执行Oracle命令的页面

commandresult为执行完Oracle命令显示结果的页面

views.py

下面为commandresult对应的函数在views.py里面的写法

    elif command_content=='check_analyzed_time':
        table_name1=[]
        try:
            db = cx_Oracle.connect(username+'/'+password+'@'+ipaddress+':'+port+'/'+tnsname ,mode=cx_Oracle.SYSDBA)
        except Exception , e:
            content= (ipaddress+' is Unreachable,The reason is '+ str(e)).strip()
            return HttpResponse(content)
        else:
            table_name  = str(request.GET['sql'])
            table_name=table_name.split()
            for i in table_name:
                table_name1.append('\''+str(i).strip().upper()+'\'')
            table_name=','.join(table_name1)
            cursor = db.cursor()
            row=getanalyzedtime(cursor,table_name)
            cursor.close()
            db.close()
            title='表分析的时间-'+ipaddress+'-'+tnsname
            tr=['OWNER','TABLE_NAME','NUM_ROWS','SAMPLE_SIZE','LAST_ANALYZED']
            dic ={'title':title,'tr':tr,'row':row}
            return render_to_response('oracle_command_result_5.html',dic)

  1. 首先获取到表单中的数据,如 ipaddress,tnsname以及执行的命令

  2. 然后通过ipaddress,tnsname从oraclelist数据库中查找获得用户名密码用于连接

  3. 再判断命令内容,如果是check_analyzed_time

  4. 则从输入文本中获取想要查询的表名并连接起来

  5. 然后执行函数获取分析时间,这里的getanalyzedtime函数获取Oracle表的分析时间,详情看具体代码

  6. 最后把页面的标题以及表格的数据放到dic变量中传到 oracle_command_result_5.html模板文件中

getanalyzedtime函数

这里我们引用getanalyzedtime函数来获取Oracle表的分析时间,具体看SQL语句

monitor/command/getoraclecommandresult.py

def getanalyzedtime(cursor,table_name):
   fp1='SELECT owner,table_name,num_rows,sample_size,last_analyzed FROM DBA_TABLES WHERE  TABLE_NAME in ('+table_name+') order by table_name'
   s=cursor.execute(fp1)
   row=s.fetchall()
   return row

template文件

这里我们依旧使用oracle_command_result_5.html文件来显示

oracle_command_result_5.html

<div id='newadd'>
<h3>{{title}}</h3>
<table class="table">
  <thead>
    <tr>
{% for i in tr %}
        <th>{{i}}</th>
{%endfor%}
    </tr>
  </thead>
{% for a,b,c,d,e in row %}
<tbody>
            <tr>
                <td>{{a}}</td>
                <td>{{b}}</td>
                <td>{{c}}</td>
                <td>{{d}}</td>
                <td>{{e}}</td>
            </tr>
</tbody>
{% endfor %}
</table>
</div>

该模板是一个table ,通过将传过来的变量显示在前端页面

实际效果

多个表一起查询请使用空格隔开

http://10.65.202.218:8081/monitor/oracle_command/

Alt text

源码地址

源码请查看我的GitHub主页

https://github.com/bsbforever/wechat_monitor

下期将介绍如何如何通过Django获取Oracle数据库段的大小