杰瑞科技汇

Java中如何插入timestamp类型数据?

Java 中插入 Timestamp 的方法

在 Java 中插入 Timestamp 到数据库(如 MySQL、PostgreSQL 等)有几种常见方法,以下是几种主要实现方式:

Java中如何插入timestamp类型数据?-图1
(图片来源网络,侵删)

使用 java.sql.Timestamp

import java.sql.Timestamp;
import java.util.Date;
// 创建当前时间的 Timestamp
Timestamp now = new Timestamp(new Date().getTime());
// 或者使用 System.currentTimeMillis()
Timestamp now = new Timestamp(System.currentTimeMillis());
// 插入数据库示例(使用 JDBC)
String sql = "INSERT INTO my_table (name, created_at) VALUES (?, ?)";
try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
    pstmt.setString(1, "Example");
    pstmt.setTimestamp(2, now);
    pstmt.executeUpdate();
}

使用 Java 8 的 java.time API(推荐)

Java 8 引入了更现代的日期时间 API,推荐使用:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.sql.Timestamp;
// 获取当前时间并转换为 Timestamp
LocalDateTime now = LocalDateTime.now();
Timestamp timestamp = Timestamp.valueOf(now);
// 或者带时区
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
Timestamp timestamp = Timestamp.from(zonedDateTime.toInstant());
// 插入数据库
String sql = "INSERT INTO my_table (name, created_at) VALUES (?, ?)";
try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
    pstmt.setString(1, "Example");
    pstmt.setTimestamp(2, timestamp);
    pstmt.executeUpdate();
}

使用 JPA/Hibernate 注解

如果使用 JPA,可以在实体类上使用注解:

import javax.persistence.*;
import java.sql.Timestamp;
@Entity
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @Column(name = "created_at")
    private Timestamp createdAt;
    // 自动设置创建时间
    @PrePersist
    protected void onCreate() {
        createdAt = new Timestamp(System.currentTimeMillis());
    }
    // getters and setters
}

或者使用 JPA 2.1+ 的 @CreationTimestamp 注解(需要 Hibernate 支持):

import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @CreationTimestamp
    @Column(name = "created_at", updatable = false)
    private Timestamp createdAt;
    // getters and setters
}

使用 MyBatis

在 MyBatis 中插入 Timestamp:

Java中如何插入timestamp类型数据?-图2
(图片来源网络,侵删)
<insert id="insertExample" parameterType="com.example.Example">
    INSERT INTO my_table (name, created_at)
    VALUES (#{name}, #{createdAt, jdbcType=TIMESTAMP})
</insert>

或者在 Java 代码中设置:

Example example = new Example();
example.setName("Test");
example.setCreatedAt(new Timestamp(System.currentTimeMillis()));
sqlSession.insert("com.example.mapper.ExampleMapper.insertExample", example);

注意事项

  1. 时区问题:确保数据库和应用程序使用相同的时区设置
  2. 精度:Timestamp 可以精确到纳秒,但数据库可能不支持这么高的精度
  3. 使用参数化查询:始终使用 PreparedStatement 而不是字符串拼接来防止 SQL 注入
  4. Java 8+:推荐使用 java.time API 而不是旧的 java.util.Date 和 java.sql.Timestamp

方法可以根据你的具体需求和技术栈选择合适的实现方式。

Java中如何插入timestamp类型数据?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇