1. 程式人生 > 其它 >【資料庫程式設計】3.ResultSet結果集

【資料庫程式設計】3.ResultSet結果集

1. ResultSet基本介紹

  1. ResultSet表示資料庫結果集的資料表,通過執行查詢資料庫的語句生成。
  2. ResultSet物件保持一個游標指向當前的資料行。最初,游標位於第一行之前。
  3. 呼叫next方法會將游標移動到下一行,如果在ResultSet物件中沒有更多行是返回false,因此使用while迴圈來遍歷結果集。

2.案例

資料表結構如下:

CREATE TABLE `demo` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(32) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

並且在demo表中插入了5條記錄:

INSERT INTO demo
VALUES (1, 'alan'),
	(2, 'mike'),
	(3, 'lucy'),
	(4, 'jack'),
	(5, 'mary');

編寫Java程式碼獲取到所有資料,並通過while迴圈遍歷打印出所有的資料,程式碼如下:

@Test
public void testResultSet() throws Exception {
    // 獲取值
    Properties properties = new Properties();
    properties.load(new FileInputStream("src\\mysql.properties"));
    String user = properties.getProperty("user");
    String password = properties.getProperty("password");
    String dirver = properties.getProperty("dirver");
    String url = properties.getProperty("url");
    // 註冊驅動
    Class.forName(dirver);
    // 得到連線和Statement
    Connection connection = DriverManager.getConnection(url, user, password);
    Statement statement = connection.createStatement();
    // 組織SQL
    String sql = "select * from demo";
    // 執行SQL獲得結果集
    ResultSet resultSet = statement.executeQuery(sql);
    
    // 遍歷結果集
    while (resultSet.next()) {
        int id = resultSet.getInt("id");
        String name = resultSet.getString("name");
        System.out.println(id + "\t" + name);
    }
    
    // 關閉連線
    resultSet.close();
    statement.close();
    connection.close();
}

得到如下結果: