Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Tạo danh sách (List) từ bảng MySQL trong Java (ArrayList lồng nhau)

Giới thiệu

Khi truy xuất dữ liệu từ MySQL bằng JDBC, thường lưu vào ArrayList<ArrayList<String>> (danh sách các hàng, mỗi hàng là danh sách các cột) để xử lý trong Java.

Ví dụ hoàn chỉnh

Bước 1: Tạo bảng và dữ liệu

CREATE TABLE demo10 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(20)
);
INSERT INTO demo10 (name) VALUES ('John'), ('Bob'), ('David');

Bước 2: Code Java

import java.sql.*;
import java.util.ArrayList;

public class ListInListDemo {
    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;
        try {
            ArrayList> outer = new ArrayList<>();
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
            stmt = con.createStatement();
            String sql = "SELECT * FROM demo10";
            ResultSet rs = stmt.executeQuery(sql);
            
            while (rs.next()) {
                ArrayList inner = new ArrayList<>();
                inner.add(rs.getString("name"));
                outer.add(inner);
            }
            
            System.out.println("The names are as follows:");
            for (int i = 0; i < outer.size(); i++) {
                System.out.println(outer.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Kết quả:

The names are as follows:
[John]
[Bob]
[David]

Mở rộng: Thêm các cột khác vào inner list, hoặc dùng ArrayList<Map<String, Object>> để giữ tên cột.