您的位置:首页 > 编程语言 > Java开发

JDK6笔记(5)----JDBC4(5)

2007-04-09 11:12 204 查看
JDK6笔记(5)----JDBC4(5)
1、ResultSet接口你可以指定三种常量:
1)TYPE_FORWARD_ONLY
结果集游标只能从开始到最后进行前移,它不能后退。而且,结果集对数据源的改变不敏感。
2)TYPE_SCROLL_INSENSITIVE
结果集游标能前移和后移,也能跳转到应用程序指定的行。而且,结果集对数据源的改变不敏感。
3)TYPE_SCROLL_SENSITIVE
结果集游标能前移和后移,也能跳转到应用程序指定的行。在结果集打开时,结果集对于数据源的改变很敏感。它提供了面向数据的动态视图。
2、设置结果集的并行性
结果集有两种并行性:一是read-only(只读);二是updatable(可更新)。要查找你的JDBC驱动器是否支持结果集的并行性,可使用DatabaseMetaData.supportResultSetConcurrency()方法来查询。
ResultSet接口可指定两种常量:
1)CONCUR_READ_ONLY
指定结果集是只读的,不能进行动态更新;
2)CONCUR_UPDATABLE
指定结果集可动态更新。
3、设置结果集的持续性
结果集通常在事务处理完后就自动关闭了。在ResultSet接口中Connection.commmit有下面的常量:
1)HOLD_CURSORS_OVER_COMMIT
指定当Connection.commit调用时,结果集对象不关闭。此时,它将维持,直到程序调用Result.close方法来关闭。
2)CLOSE_CURSORS_AT_COMMIT
指定当Connection.commit出现后,就关闭ResultSet对象。
下面是使用结果集的例子:
//Look up the registered data source from JNDI
DataSource dsDataSource =(DataSource)ctx.lookup("jdbc/mydb");
//obtain a Connection object from the data source
Connection cConn=dsDataSource.getConnection("sa","password");
Statement sStatement=cConn.createStatement(
ResultSet.CONCUR_UPDATABLE,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
ResultRest rsResults=sStatement.executeQuery("SELECT NAME, TEAM FROM PLAYERS");
//Though we hava not done anything to warrant a commit we put this here to show where the ResultSet
//would be closed
cConn.commit();
//Close the connection
cConn.close();

4、处理结果集的例子
Statement sStatement=cConn.createStatement(
ResultSet.CONCUR_UPDATABLE,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
ResultSet rsResults=sStatement.executeQuery("SELECT NAME,TEAM,AGE, "+"RANK FROM PLAYERS");
//Move to the last row
rsResults.last();
//Update specific data in the row
rsResults.updateString(2,"Hornets");
rsResults.updateInt(3,27);
rsResults.updateLong(4,5021);
//Commit the changes to the row
rsResults.updateRow();
cConn.commit();
//close the connection
cConn.close();

5、插入、删除的例子
Statement sStatement=cConn.createStatement(ResultSet.CONCUR_UPDATABLE);
ResultSet rsResults=sStatement.executeQuery("SELECT NAME,TEAM,AGE,"+ "RANK FROM PLAYERS");
//Move to the fourth row
rsResults.absolute(4);
rsResults.deleteRow();
//Now let's insert a new row
rsResults.moveToInsertRow();
//Build data for new row
rsResults.updateString(1,"Ken Pratt");
rsResults.updateString(2,"Tigers");
rsResults.updateInt(3,32);
rsResults.updateLong(4,7521);
//Add the new row to the ResultSet
rsResults.insertRow();
//Move the cursor back the original position
rsResults.moveToCurrentRow();
//Commit changes
cConn.commit();
//Close the connection
cConn.close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: