检查未绑定变量的语句(硬解析状况)

上节我们介绍了如何通过Django获取Oracle 执行次数等于一的语句,而这些语句很有可能是未使用绑定变量导致,这节讲如何获取其具体的信息

开发环境

操作系统: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_unboundsql':
        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:
            unboundsql  = str(request.GET['sql'])
            #return HttpResponse(unboundsql)
            cursor = db.cursor()
            row=getunboundsql(cursor,unboundsql)
            cursor.close()
            db.close()
            title='未绑定变量语句-'+ipaddress+'-'+tnsname
            tr=['SQL语句','哈希值','模块','第一次载入时间','上一次载入时间']
            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_unboundsql

  4. 则首先获取上节中查找到的执行次数等于一的语句,

  5. 然后将语句作为参数传递到函数getunboundsql中未使用绑定变量的语句的相信信息,详情看具体代码

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

getunboundsql函数

这里的getunboundsql函数获取执行次数等于一的语句,详情看具体代码

monitor/command/getoraclecommandresult.py

def getunboundsql(cursor,unboundsql):
   fp=open('/home/oracle/mysite/monitor/command/oracle_command/getunboundsql.sql','r')
   fp1=fp.read().strip()+unboundsql+'%\' order by last_load_time desc'
   s=cursor.execute(fp1)
   fp.close()
   row=s.fetchall()
   return row
getexecutions.sql

这个SQL获取v$sql视图中未使用绑定变量的语句情况

getunboundsql.sql

select sql_text, hash_value, module , first_load_time, last_load_time
 from v$sql
where sql_text like '

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>

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

实际效果

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

Alt text

从上面结果我们可以看到这个select语句的where子句未使用绑定变量

从模块中可以看到其来自的哪里,载入时间也可以判断其执行的非常频繁。

源码地址

源码请查看我的GitHub主页

https://github.com/bsbforever/wechat_monitor

到这里已经讲了日常运维中遇到的情形,大家如有其他需求,基本上都提供了模板供修改