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

วิธี Insert ข้อมูลใน MySQL ด้วย Java (JDBC)

คำสั่ง SQL

INSERT INTO yourTableName (col1, col2, ...) VALUES (val1, val2, ...);

ตัวอย่างโค้ด Java (JDBC)

import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class JavaInsertDemo {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            
            conn = (Connection) DriverManager.getConnection(
                "jdbc:mysql://localhost/business", "Manish", "123456");
            System.out.println("Connection is created successfully:");
            
            stmt = (Statement) conn.createStatement();
            
            String query1 = "INSERT INTO InsertDemo VALUES (1, 'John', 34)";
            stmt.executeUpdate(query1);
            
            query1 = "INSERT INTO InsertDemo VALUES (2, 'Carol', 42)";
            stmt.executeUpdate(query1);
            
            System.out.println("Record is inserted in the table successfully...");
        } catch (SQLException excep) {
            excep.printStackTrace();
        } catch (Exception excep) {
            excep.printStackTrace();
        } finally {
            try { if (stmt != null) stmt.close(); } catch (SQLException se) {}
            try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); }
        }
        System.out.println("Please check MySQL Table...");
    }
}

ตรวจสอบใน MySQL

mysql> select * from InsertDemo;
+------+-------+------+
| Id   | Name  | Age  |
+------+-------+------+
| 1    | John  | 34   |
| 2    | Carol | 42   |
+------+-------+------+

แนะนำ: ใช้ PreparedStatement

String sql = "INSERT INTO InsertDemo (Id, Name, Age) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.setString(2, "John");
pstmt.setInt(3, 34);
pstmt.executeUpdate();

PreparedStatement ป้องกัน SQL Injection และเร็วกว่าสำหรับ Batch Insert

หมายเหตุ: ไดรเวอร์ใหม่ควรใช้ com.mysql.cj.jdbc.Driver