JDBC結果集
- SQL語句執行后從數據庫查詢讀取數據,返回的數據放在結果集中 ResultSet接口表示數據庫查詢的結果集。
- ResultSet對象維護指向結果集中當前行的游標。 術語“結果集”是指包含在ResultSet對象中的行和列數據。
瀏覽結果集
編號 | 方法 | 描述 |
---|---|---|
1 | public void beforeFirst() throws SQLException | 將光標移動到第一行之前 |
2 | public void afterLast() throws SQLException | 將光標移動到最后一行之后。 |
3 | public boolean first() throws SQLException | 將光標移動到第一行。 |
4 | public void last() throws SQLException | 將光標移動到最后一行。 |
5 | public boolean absolute(int row) throws SQLException | 將光標移動到指定的行。 |
6 | public boolean relative(int row) throws SQLException | 從當前指向的位置,將光標向前或向后移動給定行數。 |
7 | public boolean previous() throws SQLException | 將光標移動到上一行。 如果上一行關閉結果集,此方法返回false。 |
8 | public boolean next() throws SQLException | 將光標移動到下一行。 如果結果集中沒有更多行,則此方法返回false。 |
9 | public int getRow() throws SQLException | 返回光標指向的行號。 |
10 | public void moveToInsertRow() throws SQLException | 將光標移動到結果集中的特殊行,該行可用於將新行插入數據庫。當前光標位置被記住。 |
11 | public void moveToCurrentRow() throws SQLException | 如果光標當前位於插入行,則將光標移回當前行; 否則,此方法什么也不做 |
查看結果集
編號 | 方法 | 描述 |
---|---|---|
序號 | 方法 | 描述 |
1 | public int getInt(String columnName) throws SQLException | 返回名為columnName的列中當前行中的int值。 |
2 | public int getInt(int columnIndex) throws SQLException | 返回指定列索引當前行中的int值。列索引從1開始,意味着行的第一列為1,行的第二列為2,依此類推。 |
類似地,在八個Java基元類型中的每一個的ResultSet接口中都有get方法,以及常見的類型,如java.lang.String,java.lang.Object和java.net.URL等。
簡單使用
/*
* 簡單數據獲取遍歷
* */
public void selectEasy() {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
String sql = "select * from user limit 0,50";
try {
//獲取數據連接
connection = basicUse.getConnection();
//獲取發送sql指令執行sql對象
statement = connection.createStatement();
//返回查詢結果集用於保存數據庫查詢內容
rs = statement.executeQuery(sql);
//遍歷結果集拿到數據
//next()---------------類似指針的效果,會向下移動;
while (rs.next()) {
// getString(String columnname)-------------根據列名獲取本列的值;
//getString(int index)--------------根據索引獲取指定位置的值;
System.out.println("id" + "\t" + rs.getString(1));
System.out.println("name" + "\t" + rs.getString(2));
System.out.println("age" + "\t" + rs.getString("age"));
System.out.println("email" + "\t" + rs.getString("email"));
System.out.println("manager_id" + "\t" + rs.getString("manager_id"));
System.out.println("create_time" + "\t" + rs.getString("create_time"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//執行完數據庫操作后記得關閉數據庫連接資源
try {
rs.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
完整項目案例
點擊這里 github