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

การ Insert ข้อมูลใน MySQL ด้วย Java (JDBC)

ตัวอย่างการเชื่อมต่อและ Insert ข้อมูล MySQL จาก Java ด้วย JDBC Statement

สร้างตารางใน MySQL

mysql> create table DemoTable( 
    Id int, 
    Name varchar(30), 
    CountryName varchar(30), 
    Age int ); 
Query OK, 0 rows affected (0.66 sec)

โค้ด Java (JDBC Statement)

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

public class AccessMySQLDatabase {
    public static void main(String[] args) {
        Connection con = null;
        Statement st = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/web?" + "useSSL=false", "root", "123456");
            st = con.createStatement();
            String accessDatabase = "insert into DemoTable(Id,Name,CountryName,Age)" + " values(100,'David','AUS',24) ";
            int result = st.executeUpdate(accessDatabase);
            if (result > 0) {
                System.out.println("Record Inserted! Check your table now!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (st != null) st.close(); } catch (Exception e) {}
            try { if (con != null) con.close(); } catch (Exception e) {}
        }
    }
}

ผลลัพธ์

Record Inserted! Check your table now!

ตรวจสอบใน MySQL

Mysql> select * from DemoTable;
+------+-------+-------------+------+
| Id   | Name  | CountryName | Age  |
+------+-------+-------------+------+
|  100 | David | AUS         |   24 |
+------+-------+-------------+------+
1 row in set (0.00 sec)

การ Insert ข้อมูลใน MySQL ด้วย Java (JDBC)

แนวทางปฏิบัติที่ดีกว่า: ใช้ PreparedStatement

String sql = "INSERT INTO DemoTable(Id, Name, CountryName, Age) VALUES (?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 100);
ps.setString(2, "David");
ps.setString(3, "AUS");
ps.setInt(4, 24);
ps.executeUpdate();

ข้อดีของ PreparedStatement

  • ป้องกัน SQL Injection
  • ประสิทธิภาพดีกว่า (Query plan reuse)
  • จัดการ Escape character อัตโนมัติ
  • รองรับ Batch Insert: ps.addBatch(); ps.executeBatch();

การจัดการ Resource (Java 7+ Try-with-resources)

try (Connection con = DriverManager.getConnection(url, user, pass);
     PreparedStatement ps = con.prepareStatement(sql)) {
    ps.setInt(1, 100);
    // ...
    ps.executeUpdate();
} // Auto-close