JAVA 数据库编程中的性能优化

1、 禁止自动提交:
在默认情况下,程序执行的任何sql语句都是自动提交的
向一个表中插入2000条记录,
自动提交所用的时间11666毫秒
禁止自动提交(显示提交)3450毫秒

2、 批处理:
多用批处理,减少操作数据库次数。
(1)、禁止自动提交
setAutoCommit(false);
(2)、准备一个语句对象
PreparedStatementmyPrepStatement=myConnection.prepareStatement(“insertintotest_tab(value)values(?)”;
(3)、将语句添加进批中
addBatch();
(4)、执行这批语句
executeBatch();
(5)、提交执行的语句
myConnection.commit();

Oracle新的改进后的批处理:(JDBC2.0以上支持)
只能对OraclePreparedStatement对象进行处理,其中的sql语句在5-30个是最优化的)
改进的地方是,可以预设批大小,SQL语句就会自动添加进批中。
(1)、禁止提交
(2)、设置批值
myoracleConnection.setDefaultExecuteBatch(10);
(3)、对SQL语句进行批处理
for(intcount=0;count<20;count++){
myOraclePrepStatement.setInt(1,count);
introwsInserted=myOraclePrepStatement.executeUpdate();
}
注:还可以强制执行introwsInserted=myOraclePrepStatement.sendBatch();

3、 行预获取
默认情况下,结果集获取的行数是10,对大多数程序都是合适的,但是,如果要获取的行非常多,那么可以增加获取尺寸以便进一步提高程序性能。
通常采用Oracle行预获取,而不用标用行预获取

标准行预获取
StatementmyStatement=myConnection.CreateStatement();
myStatement.setFetchSize(20);
从数据库取2000条记录
当设为11642毫秒
10 161毫秒
20 91毫秒

Oracle行预获取
OracleStatementmyOracleStatement=(OracleSTatement)myConntion.CreateStatement();
myOracleStatement.setRowPrefetch(20);

当设为11532毫秒
11 140毫秒
21 80毫秒


4、 定义结果集类型及长度
预先定义结果集列的Java类型,可以节省判断结果集类型往返。
当查询发送到数据库时,会有一次往返判断结果集应该使用的Java类型。
((OracleStatement)myStatement).defineColumnType(1,java.sql.Types.INTEGER);

5、 语句缓存
使用缓存的语句,通常可以将准备语句的时间减少一半,同时还要以避免使用结果集时创建新的游标。
两种类型:
隐式语句缓存
前后两次使用的语句字符串完全一样。
显示语缓存
((OracleStatement)myPrepStatement).closeWithKey(“myCachedStatement”);
6、 数据类型定义
定义成与SQL一样的数据类型。
7、 变量名定义规则
变量大小写一至,SQL语句字符串大小写一至。

>>>等值关联
selecta.id,a.title,b.columnid
fromarticleinfoa,articlecolumnb
wherea.id=b.articlei;

>>>外关联
selecta.id,a.title,b.columnid
fromarticleinfoa,articlecolumnb
wherea.id=b.articlei(+)andb.articleidnotnull;

>>>内关联
selecta.id,a.title,b.columnid
fromarticleinfoa,articlecolumnb
whereb.articlei(+)=a.idandb.articleidnotnull;

>>>等值关联
selecta.id,a.title
fromarticleinfoa,articlecolumnb
wherea.id=b.articleid;

>>>IN关联
Selecta.id,a.titlefromarticleinfoa
Wherea.idin(selectarticleidfromarticlecolumnb);

>>>等值关联(40%)
selecta.id,a.title
fromarticleinfoa
whereexists(selectb.articleidfromarticlecolumnb
wherea.id=b.articleid);

>>>创建函数索引
selecta.id,a.title
fromarticleinfo
wheretrunc(entertime)>=sysdate-30;

createindexfun_trunc_entertimeonarticleinfo(trunc(entertime))

>>>显示使用某个索引
select/*+articleinfo(fun_trunc_entertime)*/idfromarticleinfo
wheretrunc(entertime)>=sysdate-30;

>>>Where子句中的条件顺序
范围越小越靠后
selecta.id,b.columnidfromarticleinfoa,articlecolumnb
wherea.id=b.articleid(+)andb.articleidisnotnullandb.columnid>=353454564564576andb.columnid<234345344565676;
• NestedLoops(NL)Join
• Sort-MergeJoin
• HashJoin(notavailablewiththeRBO)
• ClusterJoin

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值