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

ResultSet ใน JDBC คืออะไร และการดึงข้อมูลจาก ResultSet object


อินเทอร์เฟซ ResultSet ใน JDBC แสดงข้อมูลตารางจากคำสั่ง SQL มี cursor ชี้แถวปัจจุบัน เริ่มต้นอยู่ก่อนแถวแรก

ResultSet ใน JDBC คืออะไร และการดึงข้อมูลจาก ResultSet object

การเคลื่อน pointer ใน ResultSet

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

while(rs.next()) { }

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

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

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

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

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

ตัวอย่าง

ตาราง dataset ข้อมูลยอดขายมือถือ:

+--------------+-----------+
| mobile_brand | unit_sale |
+--------------+-----------+
| Iphone       | 3000      |
| Samsung      | 4000      |
| Nokia        | 5000      |
| Vivo         | 1500      |
| Oppo         | 900       |
| MI           | 6400      |
| MotoG        | 4360      |
| Lenovo       | 4100      |
| RedMi        | 4000      |
| MotoG        | 4360      |
| OnePlus      | 6334      |
+--------------+-----------+

ตัวอย่างโปรแกรม

ดึงข้อมูลทั้งหมดและพิมพ์:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class RetrievingData {
    public static void main(String args[]) throws Exception {
        // ลงทะเบียน Driver
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        // เชื่อมต่อ
        String mysqlUrl = "jdbc:mysql://localhost/TestDB";
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
        System.out.println("Connection established......");
        // สร้าง Statement
        Statement stmt = con.createStatement();
        // ดึงข้อมูล
        ResultSet rs = stmt.executeQuery("select * from Dataset");
        System.out.println("Contents of the table");
        while(rs.next()) {
            System.out.print("Brand: " + rs.getString("Mobile_Brand") + ", ");
            System.out.print("Sale: " + rs.getString("Unit_Sale"));
            System.out.println();
        }
    }
}

ผลลัพธ์

Connection established......
Contents of the table
Brand: Iphone, Sale: 3000
Brand: Samsung, Sale: 4000
Brand: Nokia, Sale: 5000
Brand: Vivo, Sale: 1500
Brand: Oppo, Sale: 900
Brand: MI, Sale: 6400
Brand: MotoG, Sale: 4360
Brand: Lenovo, Sale: 4100
Brand: RedMi, Sale: 4000
Brand: MotoG, Sale: 4360
Brand: OnePlus, Sale: 6334