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

การเพิ่มเดือนในวันที่ปัจจุบันจาก Java กับ MySQL

การใช้ INTERVAL ใน MySQL ผ่าน Java JDBC

สามารถคำนวณวันที่ใน SQL ได้โดยตรงด้วย CURDATE() + INTERVAL n MONTH แล้วส่งผ่าน PreparedStatement

SQL Query

INSERT INTO demo12 (created_date) 
VALUES (CURDATE() + INTERVAL 2 MONTH)

โค้ด Java (JDBC)

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

public class AddSomeMonthDemo {
    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
            stmt = con.createStatement();
            
            String query = "INSERT INTO demo12 VALUES (CURDATE() + INTERVAL 2 MONTH)";
            int status = stmt.executeUpdate(query);
            
            if (status > 0) {
                System.out.println("Record inserted successfully");
            } else {
                System.out.println("Error: not inserted");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

หมายเหตุสำคัญ:

  • ใช้ PreparedStatement แทน Statement เพื่อป้องกัน SQL Injection
  • Driver class com.mysql.jdbc.Driver เป็นรูปแบบเก่า (MySQL Connector/J 5.x) เวอร์ชันใหม่ใช้ com.mysql.cj.jdbc.Driver
  • ควรใช้ Try-with-resources เพื่อปิด Connection อัตโนมัติ

ผลลัพธ์: หากวันนี้ 2020-10-25 จะแทรกวันที่ 2020-12-25