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

ดึงคอลัมน์เฉพาะจากตารางด้วยโปรแกรม JDBC


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

ใช้เมธอด next() เคลื่อน cursor และเมธอด getter (getInt(), getString(), getDate() ฯลฯ) ดึงค่าคอลัมน์

ขั้นตอนดึงข้อมูลเฉพาะคอลัมน์:

  • เชื่อมต่อฐานข้อมูล
  • สร้าง Statement object
  • รันคำสั่งด้วย executeQuery() ส่งคำสั่ง SELECT แบบระบุชื่อคอลัมน์ เช่น select Name, DOB from Emp

ตัวอย่าง

สมมติตาราง Emp มีโครงสร้าง:

+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| Name     | varchar(255) | YES  |     | NULL    |       |
| DOB      | date         | YES  |     | NULL    |       |
| Location | varchar(255) | YES  |     | NULL    |       |
+----------+--------------+------+-----+---------+-------+

โปรแกรม JDBC ดึง Name และ DOB:

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

public class RetrievingParticularColumn {
    public static void main(String args[]) throws Exception {
        // ลงทะเบียน Driver
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        // เชื่อมต่อ
        String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
        System.out.println("Connection established......");
        // สร้าง Statement
        Statement stmt = con.createStatement();
        // ดึงข้อมูลคอลัมน์เฉพาะ
        ResultSet rs = stmt.executeQuery("select Name, DOB from Emp");
        System.out.println("Contents of the table");
        while(rs.next()) {
            System.out.print("Name of the Employee: " + rs.getString("Name") + ", ");
            System.out.print("Date of Birth: " + rs.getDate("DOB"));
            System.out.println();
        }
    }
}

ผลลัพธ์

Connection established......
Contents of the table
Name of the Employee: Amit, Date of Birth: 1970-01-08
Name of the Employee: Sumith, Date of Birth: 1970-01-08
Name of the Employee: Sudha, Date of Birth: 1970-01-05