JDBC的结果集
以下內容引用自http://wiki.jikexueyuan.com/project/jdbc/result-sets.html:
SQL語句從數據庫查詢中獲取數據,并將數據返回到結果集中。SELECT語句是一種標準的方法,它從一個數據庫中選擇行記錄,并顯示在一個結果集中。java.sql.ResultSet接口表示一個數據庫查詢的結果集。
一個ResultSet對象控制一個光標指向當前行的結果集。術語“結果集”是指包含在ResultSet對象中的行和列的數據。
ResultSet接口的方法可細分為三類:
- 導航方法(Navigational):用于移動光標。
- 獲取方法(Get):用于查看當前行被光標所指向的列中的數據。
- 更新方法(Update):用于更新當前行的列中的數據。這些更新也會更新數據庫中的數據。
光標的移動基于ResultSet的屬性。用相應的語句生成ResultSet對象時,同時生成ResultSet的屬性。
JDBC提供了連接方法通過下列創建語句來生成所需的ResultSet對象:
- createStatement(int RSType, int RSConcurrency);
- prepareStatement(String SQL, int RSType, int RSConcurrency);
- prepareCall(String sql, int RSType, int RSConcurrency);
第一個參數表示ResultSet對象的類型,第二個參數是兩個ResultSet常量之一,該常量用于判斷該結果集是只讀的還是可修改的。
一、ResultSet的類型
可能的RSType如下所示。如果不指定ResultSet類型,將自動獲得的值是TYPE_FORWARD_ONLY。
| ResultSet.TYPE_FORWARD_ONLY | 光標只能在結果集中向前移動。 |
| ResultSet.TYPE_SCROLL_INSENSITIVE | 光標可以向前和向后移動。當結果集創建后,其他人對數據庫的操作不會影響結果集的數據。 |
| ResultSet.TYPE_SCROLL_SENSITIVE. | 光標可以向前和向后移動。當結果集創建后,其他人對數據庫的操作會影響結果集的數據。 |
二、ResultSet的并發性
RSConcurrency的值如下所示,如果不指定并發類型,將自動獲得的值是CONCUR_READ_ONLY。
| ResultSet.CONCUR_READ_ONLY | 創建一個只讀結果集,這是默認的值。 |
| ResultSet.CONCUR_UPDATABLE | 創建一個可修改的結果集。 |
到目前為止示例可以如下所示,可以寫成初始化一個Statement對象來創建一個只能前進,而且只讀的ResultSet對象:
try {Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } catch(Exception ex) {.... } finally {.... }三、導航結果集
在ResultSet接口中包括如下幾種方法涉及移動光標:
| public void beforeFirst() throws SQLException | 將光標移動到第一行之前。 |
| public void afterLast() throws SQLException | 將光標移動到最后一行之后。 |
| public boolean first() throws SQLException | 將光標移動到第一行。 |
| public void last() throws SQLException | 將光標移動到最后一行。 |
| public boolean absolute(int row) throws SQLException | 將光標移動到指定的第row行。 |
| public boolean relative(int row) throws SQLException | 將光標移動到當前指向的位置往前或往后第row行的位置。 |
| public boolean previous() throws SQLException | 將光標移動到上一行,如果超過結果集的范圍則返回false。 |
| public boolean next() throws SQLException | 將光標移動到下一行,如果是結果集的最后一行則返回false。 |
| public int getRow() throws SQLException | 返回當前光標指向的行數的值。 |
| public void moveToInsertRow() throws SQLException | 將光標移動到結果集中指定的行,可以在數據庫中插入新的一行。當前光標位置將被記住。 |
| public void moveToCurrentRow() throws SQLException | 如果光標處于插入行,則將光標返回到當前行,其他情況下,這個方法不執行任何操作。 |
示例:
//STEP 1. Import required packages import java.sql.*;public class JDBCExample {// JDBC driver name and database URLstatic final String JDBC_DRIVER = "com.mysql.jdbc.Driver";static final String DB_URL = "jdbc:mysql://localhost/Test?serverTimezone=UTC";// Database credentialsstatic final String USER = "root";static final String PASS = "root";public static void main(String[] args) {Connection conn = null;Statement stmt = null;try {// STEP 2: Register JDBC driverClass.forName("com.mysql.jdbc.Driver");// STEP 3: Open a connectionSystem.out.println("Connecting to database...");conn = DriverManager.getConnection(DB_URL, USER, PASS);// STEP 4: Execute a query to create statment with// required arguments for RS example.System.out.println("Creating statement...");stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);String sql;sql = "SELECT id, first, last, age FROM Employees";ResultSet rs = stmt.executeQuery(sql);// Move cursor to the last row.System.out.println("Moving cursor to the last...");rs.last();// STEP 5: Extract data from result setSystem.out.println("Displaying record...");// Retrieve by column nameint id = rs.getInt("id");int age = rs.getInt("age");String first = rs.getString("first");String last = rs.getString("last");// Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);// Move cursor to the first row.System.out.println("Moving cursor to the first row...");rs.first();// STEP 6: Extract data from result setSystem.out.println("Displaying record...");// Retrieve by column nameid = rs.getInt("id");age = rs.getInt("age");first = rs.getString("first");last = rs.getString("last");// Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);// Move cursor to the first row. System.out.println("Moving cursor to the next row...");rs.next();// STEP 7: Extract data from result setSystem.out.println("Displaying record...");id = rs.getInt("id");age = rs.getInt("age");first = rs.getString("first");last = rs.getString("last");// Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);// STEP 8: Clean-up environment rs.close();stmt.close();conn.close();} catch (SQLException se) {// Handle errors for JDBC se.printStackTrace();} catch (Exception e) {// Handle errors for Class.forName e.printStackTrace();} finally {// finally block used to close resourcestry {if (stmt != null)stmt.close();} catch (SQLException se2) {} // nothing we can dotry {if (conn != null)conn.close();} catch (SQLException se) {se.printStackTrace();} // end finally try} // end trySystem.out.println("Goodbye!");}// end main }// end JDBCExample這將產生如下所示結果:
四、查看結果集
ResultSet接口中含有幾十種從當前行獲取數據的方法。
每個可能的數據類型都有一個get方法,并且每個get方法有兩個版本:
- 一個需要列名。
- 一個需要列的索引。
例如,如果想查看的列包含一個int類型,需要在ResultSet中調用getInt()方法:
| public int getInt(String columnName) throws SQLException | 返回當前行中名為columnName的列的int值。 |
| public int getInt(int columnIndex) throws SQLException | 返回當前行中指定列的索引的int值。列索引從1開始,意味著行中的第一列是1 ,第二列是2 ,以此類推。 |
同樣的,在ResultSet接口中還有獲取八個Java原始類型的get方法,以及常見的類型,比如java.lang.String,java.lang.Object和java.net.URL。
也有用于獲取SQL數據類型java.sql.Date,java.sql.Time,java.sql.Timestamp,java.sql.Clob,java.sql.Blob中的方法。查看官方Java文檔可以了解使用這些SQL數據類型的更多的信息。
示例:
//STEP 1. Import required packages import java.sql.*;public class JDBCExample2 {// JDBC driver name and database URLstatic final String JDBC_DRIVER = "com.mysql.jdbc.Driver";static final String DB_URL = "jdbc:mysql://localhost/Test?serverTimezone=UTC";// Database credentialsstatic final String USER = "root";static final String PASS = "root";public static void main(String[] args) {Connection conn = null;Statement stmt = null;try {// STEP 2: Register JDBC driverClass.forName("com.mysql.jdbc.Driver");// STEP 3: Open a connectionSystem.out.println("Connecting to database...");conn = DriverManager.getConnection(DB_URL, USER, PASS);// STEP 4: Execute a query to create statment with// required arguments for RS example.System.out.println("Creating statement...");stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);String sql;sql = "SELECT id, first, last, age FROM Employees";ResultSet rs = stmt.executeQuery(sql);// Move cursor to the last row.System.out.println("Moving cursor to the last...");rs.last();// STEP 5: Extract data from result setSystem.out.println("Displaying record...");// Retrieve by column nameint id = rs.getInt("id");int age = rs.getInt("age");String first = rs.getString("first");String last = rs.getString("last");// Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);// Move cursor to the first row.System.out.println("Moving cursor to the first row...");rs.first();// STEP 6: Extract data from result setSystem.out.println("Displaying record...");// Retrieve by column nameid = rs.getInt("id");age = rs.getInt("age");first = rs.getString("first");last = rs.getString("last");// Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);// Move cursor to the first row. System.out.println("Moving cursor to the next row...");rs.next();// STEP 7: Extract data from result setSystem.out.println("Displaying record...");id = rs.getInt(1);//The first column indexage = rs.getInt("age");first = rs.getString("first");last = rs.getString("last");// Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);// STEP 8: Clean-up environment rs.close();stmt.close();conn.close();} catch (SQLException se) {// Handle errors for JDBC se.printStackTrace();} catch (Exception e) {// Handle errors for Class.forName e.printStackTrace();} finally {// finally block used to close resourcestry {if (stmt != null)stmt.close();} catch (SQLException se2) {} // nothing we can dotry {if (conn != null)conn.close();} catch (SQLException se) {se.printStackTrace();} // end finally try} // end trySystem.out.println("Goodbye!");}// end main }// end JDBCExample這將產生如下所示結果:
五、更新的結果集
ResultSet接口包含了一系列的更新方法,該方法用于更新結果集中的數據。
用get方法可以有兩個更新方法來更新任一數據類型:
- 一個需要列名。
- 一個需要列的索引。
例如,要更新一個結果集的當前行的String列,可以使用任一如下所示的updateString()方法:
| public void updateString(int columnIndex, String s) throws SQLException | 將指定列的字符串的值改為s。 |
| public void updateString(String columnName, String s) throws SQLException | 類似于前面的方法,不同之處在于指定的列是用名字來指定的,而不是它的索引。 |
八個原始數據類型都有其更新方法,比如String,Object,URL,和在java.sql包中的SQL數據類型。
更新結果集中的行將改變當前行的列中的ResultSet對象,而不是基礎數據庫中的數據。要更新數據庫中一行的數據,需要調用以下的任一方法:
| public void updateRow() | 通過更新數據庫中相對應的行來更新當前行。 |
| public void deleteRow() | 從數據庫中刪除當前行。 |
| public void refreshRow() | 在結果集中刷新數據,以反映數據庫中最新的數據變化。 |
| public void cancelRowUpdates() | 取消對當前行的任何修改。 |
| public void insertRow() | 在數據庫中插入一行。本方法只有在光標指向插入行的時候才能被調用。 |
示例:
//STEP 1. Import required packages import java.sql.*;public class JDBCExample3 {// JDBC driver name and database URLstatic final String JDBC_DRIVER = "com.mysql.jdbc.Driver";static final String DB_URL = "jdbc:mysql://localhost/Test?serverTimezone=UTC";// Database credentialsstatic final String USER = "root";static final String PASS = "root";public static void main(String[] args) {Connection conn = null;try {// STEP 2: Register JDBC driverClass.forName("com.mysql.jdbc.Driver");// STEP 3: Open a connectionSystem.out.println("Connecting to database...");conn = DriverManager.getConnection(DB_URL, USER, PASS);// STEP 4: Execute a query to create statment with// required arguments for RS example.System.out.println("Creating statement...");Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);// STEP 5: Execute a queryString sql = "SELECT id, first, last, age FROM Employees";ResultSet rs = stmt.executeQuery(sql);System.out.println("List result set for reference....");printRs(rs);// STEP 6: Loop through result set and add 5 in age// Move to BFR postion so while-loop works properly rs.beforeFirst();// STEP 7: Extract data from result setwhile (rs.next()) {// Retrieve by column nameint newAge = rs.getInt("age") + 5;rs.updateDouble("age", newAge);rs.updateRow();}System.out.println("List result set showing new ages...");printRs(rs);// Insert a record into the table.// Move to insert row and add column data with updateXXX()System.out.println("Inserting a new record...");rs.moveToInsertRow();rs.updateInt("id", 104);rs.updateString("first", "John");rs.updateString("last", "Paul");rs.updateInt("age", 40);// Commit row rs.insertRow();System.out.println("List result set showing new set...");printRs(rs);// Delete second record from the table.// Set position to second record firstrs.absolute(2);System.out.println("List the record before deleting...");// Retrieve by column nameint id = rs.getInt("id");int age = rs.getInt("age");String first = rs.getString("first");String last = rs.getString("last");// Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);// Delete row rs.deleteRow();System.out.println("List result set after deleting one records...");printRs(rs);// STEP 8: Clean-up environment rs.close();stmt.close();conn.close();} catch (SQLException se) {// Handle errors for JDBC se.printStackTrace();} catch (Exception e) {// Handle errors for Class.forName e.printStackTrace();} finally {// finally block used to close resourcestry {if (conn != null)conn.close();} catch (SQLException se) {se.printStackTrace();} // end finally try} // end trySystem.out.println("Goodbye!");}// end mainpublic static void printRs(ResultSet rs) throws SQLException {// Ensure we start with first row rs.beforeFirst();while (rs.next()) {// Retrieve by column nameint id = rs.getInt("id");int age = rs.getInt("age");String first = rs.getString("first");String last = rs.getString("last");// Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);}System.out.println();}// end printRs() }// end JDBCExample這將產生如下所示結果:
?
測試工程:https://github.com/easonjim/5_java_example/tree/master/jdbcbasics/test2
轉載于:https://www.cnblogs.com/EasonJim/p/6994660.html
總結
- 上一篇: jq实现点击导航栏中的任意一个跳转后被点
- 下一篇: 使用valgrind检查内存问题