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

Statement ใน JDBC คืออะไร?


อินเทอร์เฟซ Statement แสดงถึงคำสั่ง SQL แบบคงที่ (Static SQL) ใช้สำหรับสร้างและรันคำสั่ง SQL ทั่วไปผ่านโปรแกรม Java

การสร้าง Statement

คุณสามารถสร้างอ็อบเจ็กต์ของอินเทอร์เฟซนี้ได้โดยใช้เมธอด createStatement() ของอินเทอร์เฟซ Connection ตัวอย่างการสร้างดังนี้:

Statement stmt = null;
try {
    stmt = conn.createStatement();
    // ...
} catch (SQLException e) {
    // ...
} finally {
    // ...
}

การรัน Statement object

หลังจากสร้าง statement object แล้ว สามารถรันได้ด้วยเมธอด execute 3 แบบ ได้แก่ execute(), executeUpdate() และ executeQuery()

  • execute(): ใช้รันคำสั่ง SQL DDDL คืนค่า boolean บ่งบอกว่าสามารถดึง ResultSet ได้หรือไม่

  • executeUpdate(): ใช้รันคำสั่ง INSERT, UPDATE, DELETE คืนค่าจำนวนแถวที่ได้รับผลกระทบ (integer)

  • executeQuery(): ใช้รันคำสั่งที่คืนข้อมูลเป็นตาราง (เช่น SELECT) คืนค่าอ็อบเจ็กต์ ResultSet

ตัวอย่าง

โปรแกรม JDBC ต่อไปนี้สาธิตการสร้างและรัน Statement

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

public class StatementExample {
    public static void main(String args[]) throws SQLException {
        // ลงทะเบียน 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();
        // รันคำสั่ง
        String createTable = "CREATE TABLE Employee("
            + "Name VARCHAR(255), "
            + "Salary INT NOT NULL, "
            + "Location VARCHAR(255))";
        boolean bool = stmt.execute(createTable);
        String insertData = "INSERT INTO Employee("
            + "Name, Salary, Location) VALUES "
            + "('Amit', 30000, 'Hyderabad'), "
            + "('Kalyan', 40000, 'Vishakhapatnam'), "
            + "('Renuka', 50000, 'Delhi'), "
            + "('Archana', 15000, 'Mumbai')";
        int i = stmt.executeUpdate(insertData);
        System.out.println("Rows inserted: " + i);
        ResultSet rs = stmt.executeQuery("Select * from Employee");
        while(rs.next()) {
            System.out.print("Name: " + rs.getString("Name") + ", ");
            System.out.print("Salary: " + rs.getInt("Salary") + ", ");
            System.out.print("City: " + rs.getString("Location"));
            System.out.println();
        }
    }
}

ผลลัพธ์

Connection established......
Rows inserted: 4
Name: Amit, Salary: 30000, City: Hyderabad
Name: Kalyan, Salary: 40000, City: Vishakhapatnam
Name: Renuka, Salary: 50000, City: Delhi
Name: Archana, Salary: 15000, City: Mumbai