Java 和 MySQL 如何处理日期时间和时间戳?
在 Java 中与 MySQL 日期时间和时间戳进行交互
从 Java 应用程序处理 MySQL 数据库中的日期时间和时间戳时,这是必不可少的了解这些数据类型在两者中的表示和处理方式
Java 表示
在 Java 中,日期通常使用 java.util.Date 类表示,该类以毫秒精度封装日期和时间信息。
MySQL 表示
在 MySQL 中,有三种主要的日期和时间数据类型:
- DATE:仅存储日期部分(年、月、日)。
- TIME:仅存储时间部分(小时、分钟)和秒)。
- TIMESTAMP:存储日期和时间
Java 和 MySQL 之间的交互
从 MySQL 检索 TIMESTAMP 值到 Java 时,结果存储在 java.sql.Timestamp 对象中,它是 java.util.Date 的子类。使用PreparedStatement向MySQL插入日期时,应使用setTimestamp()方法将参数值设置为Timestamp对象。
示例代码
来演示如何从 Java 与 MySQL 日期时间和时间戳进行交互,请考虑以下代码:
import java.sql.*; public class DatetimeExample { public static void main(String[] args) throws SQLException { // Establish a connection to the MySQL database Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password"); // Get a timestamp object representing the current date and time Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // Create a prepared statement to insert data into the database PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO events (event_date, event_time) VALUES (?, ?)"); // Set the timestamp value as the first parameter preparedStatement.setTimestamp(1, timestamp); // Set the second parameter as the time part of the timestamp preparedStatement.setTime(2, new Time(timestamp.getTime())); // Execute the insert statement preparedStatement.executeUpdate(); // Retrieve the inserted data using a result set ResultSet resultSet = preparedStatement.executeQuery("SELECT event_date, event_time FROM events WHERE event_id = (SELECT LAST_INSERT_ID())"); // Get the timestamp from the result set Timestamp retrievedTimestamp = resultSet.getTimestamp("event_date"); // Convert the timestamp to a Java date Date retrievedDate = new Date(retrievedTimestamp.getTime()); // Print the retrieved date and time System.out.println("Retrieved date: " + retrievedDate); System.out.println("Retrieved time: " + new Time(retrievedTimestamp.getTime())); } }
中在这个示例中,我们演示了如何使用 Timestamp 对象将日期和时间部分插入 MySQL 数据库,并在 Java 中将它们作为日期和时间对象检索。
以上是Java 和 MySQL 如何处理日期时间和时间戳?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

在 Linux 中运行 MySQl(有/没有带有 phpmyadmin 的 podman 容器)

哪些流行的MySQL GUI工具(例如MySQL Workbench,PhpMyAdmin)是什么?
