Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

นำทางใน ResultSet ด้วยโปรแกรม JDBC


เมธอด next() ของ ResultSet interface เคลื่อน pointer ไปแถวถัดไป คืนค่า boolean ใช้ใน while loop วนลูป:

while(rs.next()) { }

ดึงค่าคอลัมน์แต่ละแถว

ResultSet มีเมธอด getter (getXXX()) 2 รูปแบบ:

  • getXXX(int columnIndex): รับ index คอลัมน์ คืนค่า

  • getXXX(String columnLabel): รับชื่อคอลัมน์ คืนค่า

เลือกเมธอดตามชนิดข้อมูลคอลัมน์:

while(rs.next()) {
    System.out.print("Brand: " + rs.getString("Column_Name") + ", ");
    System.out.print("Sale: " + rs.getString("Column_Name"));
    ...
    System.out.println();
}

ถ้าเป็น bi-directional ResultSet ใช้ previous() ย้อนกลับ เนื่องจาก pointer เริ่มต้นอยู่ก่อนแถวแรก ต้องย้ายไปหลังแถวสุดท้ายก่อน:

rs.afterLast();
System.out.println("Contents of the table");
while(rs.previous()) {
    System.out.print("Brand: " + rs.getString("Mobile_Brand") + ", ");
    System.out.print("Sale: " + rs.getString("Unit_Sale"));
    System.out.println();
}