# ResultSet的用法 ```java= public class Test { private static final String url=""; private static final String user=""; private static final String password=""; public static void main(String[] args) { /* Employee table資料 eid ename 111 Tom 112 Jerry 113 Donald */ try { Connection conn = DriverManager.getConnection(url, user, password); //ResultSet.TYPE_SCROLL_INSENSITIVE 會保留原先結果 //ResultSet.CONCUR_UPDATABLE 會對資料庫進行修改的操作 Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); st.execute("SELECT * FROM Employee"); ResultSet rs = st.getResultSet(); while(rs.next()) { if(rs.getInt(1)==112) { rs.updateString(2, "Jack"); } } rs.absolute(2); //因為ResultSet.TYPE_SCROLL_INSENSITIVE 會保留原先結果, 所以結果不變 System.out.println(rs.getInt(1)+""+rs.getString(2)); } catch (SQLException ex) { System.out.println("Exception is raised"); } } } ``` :::info 在建立Statement物件時指定**resultSetType**, 可指定的參數有: **ResultSet.TYPE_FORWARD_ONLY、ResultSet.TYPE_SCROLL_INSENSITIVE ResultSet.TYPE_SCROLL_SENSITIVE** 在不指定的情況下,預設是第一個,也就是只能使用next()來逐筆取得資料, 指定第二個或第三個,則可以使用ResultSet的afterLast()、previous()、absolute()、relative()等方法。 --- **ResultSet.TYPE_SCROLL_INSENSITIVE**與**ResultSet.TYPE_SCROLL_SENSITIVE** 的差別在於能否取得ResultSet改變值後的資料, **ResultSet.TYPE_SCROLL_INSENSITIVE**會保留原先結果 --- 另外還必須指定**resultSetConcurrency**,有 **ResultSet.CONCUR_READ_ONLY**與**ResultSet.CONCUR_UPDATABLE**兩個參數可以設定, 前者表示只能讀取 ResultSet的資料,後者表示可以直接使用ResultSet來操作資料庫。 ::: 以這題為例,最後結果為: The Employee table is not updated and the program prints: **112 Jerry** 因為雖然設定**ResultSet.CONCUR_UPDATABLE**會對資料庫進行修改的操作,但是設定**ResultSet.TYPE_SCROLL_INSENSITIVE**,所以會保留原先結果, 所以結果不變。 ###### tags: `ocpjp`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up