Oracle TIMESTAMP 型別精度達毫秒/微秒,含時區資訊。插入時需將字串正確轉型。本文提供 JDBC PreparedStatement 完整程式碼與純 SQL TO_TIMESTAMP 用法,涵蓋時區、格式化與常見錯誤。
CREATE TABLE test_ts ( id INTEGER, birth_ts TIMESTAMP );
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimestampInsertDemo {
static {
try { Class.forName("oracle.jdbc.driver.OracleDriver"); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
}
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521/orcl", "root", "root");
}
public static void main(String[] args) throws SQLException {
String sql = "INSERT INTO test_ts(id, birth_ts) VALUES (?, TO_TIMESTAMP(?, 'YYYY-MM-DD HH24:MI:SS'))";
try (Connection conn = getConn();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 1);
// 方式 1:Java 端格式化字串,DB 端 TO_TIMESTAMP 轉型
String nowStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
ps.setString(2, nowStr);
// 方式 2:直接傳 java.sql.Timestamp 物件(推薦,免格式化)
// ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
ps.executeUpdate();
System.out.println("插入成功");
}
}
}
YYYY-MM-DD HH24:MI:SS(24 小時制),毫秒用 FF3,微秒用 FF6ps.setTimestamp(idx, new Timestamp(System.currentTimeMillis())),JDBC 驅動自動對應 DB TIMESTAMP,最簡潔安全TIMESTAMP WITH TIME ZONE 需用 TO_TIMESTAMP_TZ,格式含 TZH:TZM 或 TZR錯誤現象 原因 修正 ORA-01830: 日期格式圖片不符 字串格式與格式模型不匹配 核對字串長度、分隔符、24/12 小時制 ORA-01843: 非有效月份 月份值 >12 或格式模型月份位置錯 確認 MM vs MON、字串實際月份 插入時間偏移數小時 DB 時區與 Session 時區不一致 用 TIMESTAMP WITH TIME ZONE 或統一 Session TIME_ZONE