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

RowSet object ใน JDBC คืออะไร? พร้อมตัวอย่าง


RowSet เป็น wrapper ของ ResultSet object สามารถเชื่อมต่อ, ตัดการเชื่อมต่อจากฐานข้อมูล และ serialize ได้ รักษาสถานะ JavaBean component ส่งผ่าน network ได้ โดยค่าเริ่มต้น scrollable และ updatable ใช้ทำให้ ResultSet ธรรมดา scrollable และ updatable ได้

สร้าง RowSet ด้วย:

RowSetProvider.newFactory().createJdbcRowSet()

ตัวอย่าง

ตาราง 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      |
+--------------+-----------+

โปรแกรมสร้าง RowSet ดึงข้อมูล:

import java.sql.DriverManager;
import javax.sql.RowSet;
import javax.sql.rowset.RowSetProvider;

public class RowSetExample {
    public static void main(String args[]) throws Exception {
        // ลงทะเบียน Driver
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        // สร้าง RowSet object
        RowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
        // ตั้งค่า URL
        String mysqlUrl = "jdbc:mysql://localhost/TestDB";
        rowSet.setUrl(mysqlUrl);
        // ตั้งค่า user/password
        rowSet.setUsername("root");
        rowSet.setPassword("password");
        // ตั้งค่า query
        rowSet.setCommand("select * from Dataset");
        System.out.println("Contents of the table");
        while(rowSet.next()) {
            System.out.print("Brand: " + rowSet.getString(1) + ", ");
            System.out.print("Sale: " + rowSet.getString(2));
            System.out.println();
        }
    }
}

ผลลัพธ์

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