如何获取Java中的时间戳并存储在MySQL数据库中? [英] How to obtain a timestamp in Java and store in MySQL database?

查看:1974
本文介绍了如何获取Java中的时间戳并存储在MySQL数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用MVC padagim的基本CMS使用JSP / Servlet技术。
添加新帖时,我想获取创建该帖子的日期和时间,并将其存储为TIMESTAMP或DATATIME数据类型。
最好的方法是什么?我该怎么办?

I'm developing a basic CMS uses JSP/Servlet Technology using the MVC padagim. When a new post is added I want to get the date and time the post was created and store it as TIMESTAMP or DATATIME data type. What is the best way to do it? And how do I Do it?

算法应该像这样

在一个java web程序(如servlet)中

In a java web program (such as servlet)


  1. 获取时间戳(当前时间)

  2. 存储在变量中的时间戳

  3. 传递sql查询以将时间戳记存储在mysql db

请帮助!

我已经看到很多答案,但我不明白那些,因为我对Java和jsp技术来说都是新的!

I have seen many answers, but I Don't understand those as I'm quite new to Java and jsp technology!

推荐答案

一个更好的处理方式在数据库端。创建表时,将 TIMESTAMP 列的默认值指定为

A much better way to handle this is at your database side. While creating the table specify the default value for the TIMESTAMP column as

CREATE TABLE posts (
    id INTEGER AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50) NOT NULL,
    creation_date TIMESTAMP DEFAULT NOW()
);

该示例显示了一个 CREATE TABLE 但这个概念是一样的。在插入行时,只需不要为列 creation_date 指定任何值,数据库将自动为您添加。

The example shows a CREATE TABLE for MySQL but the concept is the same. While inserting your row, just don't specify any value for the column creation_date and the database will auto populate it for you.

给定相同的表,如果要从Java插入日期,您的代码应如下所示:

Given the same table, if you want to insert the date from Java, your code should look like

// Get current time
Timestamp now = new Timestamp(new Date().getTime());

try {
    // Prepare INSERT through Connection
    PreparedStatement stmt = conn.prepareStatement(
        "INSERT INTO posts (title, creation_date) VALUES (?, ?)");

    // Bind values
    stmt.setString(1, title);
    stmt.setTimestamp(2, now);

    // Insert
    stmt.executeUpdate();
} catch (SQLException e) {
    e.printStackTrace();
}

请注意,您还需要打开一个DB 连接(上面的 conn 对象),并在完成后关闭它。如果您刚开始使用JDBC API,请查看 JDBC Basics 第一。

Note, that you would also need to open a DB Connection (the conn object above) and close it when you're done with it. If you're new to JDBC API, take a look at JDBC Basics first.

这篇关于如何获取Java中的时间戳并存储在MySQL数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆