由于实验室一个项目的关系,算法中需要比较不同查询语句的代价.
听说DB2有这个功能,经过昨天的摸索,终于对求cost有点概念(在DB2 v8.1中文版上测试)
在DB2中,一个SQL查询的cost是指执行语句的存取方案估计所必需使用的资源总量.
它是由CPU 成本(以指令数目计)和 I/O(以查找和页传送的数目计)的组合导出的。
求Cost和RUNSTATS没有关系,相关的命令是EXPLAIN,或是GUI的工具Visual Explain
可以对table index 等众多元素进行explain
相关的结果放在db2admin.EXPLAIN_STATEMENT等表中
在进行Explain之前,需要先在相关数据库中建立这些表
在DB2的安装目录SQLLIB\MISC\下有个EXPLAIN.DDL,执行它即可
(用命令中心或命令行connect database,然后在命令行敲db2 -tvf ../MISC/EXPLAIN.DDL 指定misc时跟当前目录相关)
之后,可以用explain all with snapshot for select * from stuff执行.
看结果需要select cost from db2admin.explain_statement;
GUI方式: 右键选择数据库实例,选择"Visual Explain"
选择一个SQL History中的语句,看结果
下面给出一个演示代码,比较粗糙.
将要做的改进: 用数据库连接池改进性能, 用OO思想重构代码
预计的接口如下: public static double getCost(String sql) throws GetCostException
import java.sql.*;
public class DB2Util{
public static void main(String[] args) throws Exception{
String url="jdbc:db2://10.85.38.144:sample";
String userId="Administrator";
String password="*****";
String sql="select * from administrator.org";
Class.forName("COM.ibm.db2.jdbc.net.DB2Driver").newInstance();
Connection con=DriverManager.getConnection( url, userId, password );
Statement statement=con.createStatement();
statement.execute("delete from administrator.explain_statement");
statement.execute("explain all with snapshot for "+sql);
ResultSet rs=statement.executeQuery(
"select total_cost from administrator.explain_statement "+
"where explain_level='P'");
System.out.println("Cost for '"+sql+"'");
while(rs.next()){
System.out.println(rs.getString(1));
}
rs.close();
statement.close();
con.close();
}
}