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

แทรกค่า NULL ลง MySQL จาก Java ด้วย PreparedStatement.setNull

Java Code: Insert NULL Value

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

public class InsertNullValueIntoDatabase {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        
        try {
            con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/web?useSSL=false", "root", "123456");
            
            String query = "INSERT INTO DemoTable1893(FirstName) VALUES (?)";
            ps = con.prepareStatement(query);
            
            // Set NULL value
            ps.setNull(1, Types.NULL);
            ps.executeUpdate();
            
            System.out.println("Check the DemoTable1893");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close resources
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            try { if (con != null) con.close(); } catch (Exception e) {}
        }
    }
}

ตรวจสอบใน MySQL

mysql> SELECT * FROM DemoTable1893;
+-----------+
| FirstName |
+-----------+
| NULL      |
+-----------+

setNull() Method

void setNull(int parameterIndex, int sqlType)
void setNull(int parameterIndex, int sqlType, String typeName)
  • parameterIndex: ตำแหน่ง Parameter (1-based)
  • sqlType: ชนิดข้อมูล SQL จาก java.sql.Types
  • Types.NULL: ระบุว่าเป็น NULL แบบ Generic

Types ที่ใช้บ่อย

Types.NULL, Types.INTEGER, Types.VARCHAR, Types.DATE
Types.TIMESTAMP, Types.DECIMAL, Types.BOOLEAN
Types.BLOB, Types.CLOB, Types.ARRAY

Best Practices

  • ใช้ try-with-resources (Java 7+) ปิด Resource อัตโนมัติ
  • ใช้ Connection Pool (HikariCP) ใน Production
  • Parameter Index เริ่มจาก 1 ไม่ใช่ 0
  • Batch Insert: ps.addBatch() + ps.executeBatch()

Try-with-resources Example

try (Connection con = DriverManager.getConnection(url, user, pass);
     PreparedStatement ps = con.prepareStatement(sql)) {
    
    ps.setNull(1, Types.VARCHAR);  // หรือ Types.NULL
    ps.executeUpdate();
}

ข้อควรระวัง

  • Column ต้องยอมรับ NULL (ไม่มี NOT NULL Constraint)
  • setNull(1, Types.NULL) ทำงานได้ แต่บาง Driver ชอบ Types.VARCHAR สำหรับ String Column
  • MySQL: useSSL=false สำหรับ Local Dev, Production ควรใช้ SSL