jdbc程序的性能主要由两个因素决定,一是数据库本身的性质,另一个是与数据库相对独立的jdbc应用程序接口(api)的使用.这里说的是如何正确使用jdbc编程接口,以获得更好的性能.
jdbc主要优化有:
1.选择正确的jdbc驱动程序
2.connention的优化 使用连接池来管理connection对象
3.statement的优化 使用批量更新等
4.result的优化 正确的从数据库中get数据等
(1)选择正确的jdbc驱动程序:
1 jdbc-odbc 桥
2 本地api-部分 java驱动
3 jdbc网路协议-纯java驱动
4 jdbc本地协议
最好选择 jdbc网路协议-纯java驱动 效率比较高 但需要第三方软件的支持 比如corba weblogic属于这种类型
(2)优化connection对象:
1.设置适当的参数 drivermanager.getconnection(string url,properties props);
例如: properties props=new properties();
props.put("user","wuwei");
props.put("password","wuwei");
props.put("defaultrowprefectch","30");
props.put("dufaultbatchvalue","5");
connection con=drivermanager.getconnection("jdbc:oracle:thin:@hostsstring",props);
对象可以通过设置setdefaultrowprefetch(int) 和 setdefaultbatchvalue(int) 两个参数类优化连接
2.使用连接池 可以自己写一个连接池 这样程序的灵活性强,便于移植.
apache项目开发了一套非常通用而表现非常稳定的对象池 http://jakarta.apache.org/commons/pool.htm
设计了自己的连接池后 在客户端调用建立对象
public object makeobject() throws exception{
class.forname("oracle.jdbc.driver.oracaldriver");
return drivermanager.getconnection("url","username","password");
}
销毁对象时用
public void destroyobject(object obj) throws exception{
((connection)obj.close());
}
注意几点 对象池里有没有回收机制,对象池里有机有容量限制,对象池里有多少个闲置对象(可以释放)
3.控制事务的提交 最好手动提交事务,不但可以可以保证数据原子性,而且对新能提高留下余地.
try{
connection.setautocommint(false);
// 代码 用preparedstatement 性能比statementh好.
connection.commit();
connection.setautocommit(true);
}
catch(sqlexception e){
}
finally{
//代码
if(connection!=null){
connection.close();
}
}
4.适当的选择事务的隔离级别 transaction_read_uncommited 性能最高
transaction_read_commited 快
transaction_refeatable_read 中等
ransaction_serializable 慢
(3)statement 优化
jdbc3个接口用来处理sql的执行,是statement preparedstatement callablestatement
提供适当的statement接口
批量执行sql
从数据库批量获取数据
preparedstatement 比statement性能要好 主要体现在一个sql语句多次重复执行的情况
preparedstatemnt只编译解析一次而statement每次编译一次.
批量修改数据库
statement 提供了方法addbatch(string)和executebatch()
调用方法为stmt.addbatch("isnert….."); stmt.addbatch("update…..")
stmt.executebatch();
也可以用preparedstatement从而更好的提高性能.
pstmt=conn.preparedstatement("insert into test_table(……) values(….?)");
pstmt.setstring(1,"aaa");
pstmt.addbatch();
pstmt.setstring(1,"bbb");
pstmt.addbatch();
…..
pstmt.executebatch();
批量地从数据库中取数据.
通过setfetchsize()和getfectchsize()方法来设定和查看这个参数.这个参数对体统的性能影响比较大.
这个参数太小会严重地降低程序地性能.
connection statement resultset都有这个参数,他们对性能地影响顺序是:
resultset———statement———connection
(4)优化resultset.
体现在以下几个方面
批量读取数据.合理设置resultset的getfetchsize()和setfetchsize()方法中的参数
使用正确的get和set方法
使用整数而不是字段名作为参数性能比较高,
例如 setint(1,100);
setstring(2,"aaaa");
比 setint("id","100");
setstring("name","aaaa");
性能好
设置适当的滚动方向.有3个方向fetch_forword,fetch_reverse fetch_unknown
单向滚动性能比较高.
其他方面的性能优化
及时显示的关闭connection statement resultset
其中connection可以用connetion pool处理.
使用数据库系统的强大查询功能去组织数据.这样程序运行是和数据库服务的交互次数少,数据库返回给
程序的记录条数少的多,所以性能有很大的提高.
