版權聲明:本文為部落客chszs的原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chszs/article/details/1557381
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、處理結果集的例子
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();
//close the connection
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