如何正确设置当前时间戳到这个将值插入MySql表的Java CRUD方法?

时间:2015-06-13 15:10:41

标签: java mysql sql timestamp

我将下表放入MySql数据库:

CREATE TABLE log(
    timestamp TIMESTAMP NOT NULL,
    action ENUM('addPerson', 'getPerson', 'getPeople', 'updatePerson', 'deletePerson', 'deleteAll') NOT NULL,
    PRIMARY KEY (timestamp)
);

现在我正在将一个JAVA 插入 CRUD方法实现到DAO中,但是我发现将时间戳值(用当前日期时间初始化)设置为相关的一些问题准备好了。

所以我正在做这样的事情:

public void addEntry(String message) throws SQLException {
    // The Connection object is a singleton and the used connection is the same for all the CRUD methods:
    Connection conn = Database.getInstance().getConnection();

    PreparedStatement p = conn.prepareStatement("insert into log (timestamp, action) values (?,?)");

    p.setTimestamp(1, new Timestamp(time));
}

但是由于它需要值,因此在创建时间戳对象时会出错。所以我认为这不是我想要的!

如何将其设置为当前时间戳(当前日期时间)?

TNX

2 个答案:

答案 0 :(得分:1)

试试这个:from django.contrib import admin from myapp.models import Client, Item, Order, Ordering class ClientAdmin(admin.ModelAdmin): list_display = ("f_name", "l_name", "m_name", "phone", "city", "address") list_filter = ["f_name", "l_name", "city"] class ItemAdmin(admin.ModelAdmin): list_display = ("name", "type_item", "color", "cost", "is_available_now", "available_count") list_filter = ["name", "type_item", "color", "cost", "available_count"] class OrderingAdmin(admin.ModelAdmin): list_display = ("id_order", "id_item", "count_items") list_filter = ["id_order", "id_item", "count_items"] class OrderingInline(admin.TabularInline): model = Ordering fk_name = "id_order" max_num = 1 class OrderAdmin(admin.ModelAdmin): list_display = ("id", "id_client", "date_order", "date_taken", "is_paid", "is_taken") list_filter = ["date_order", "date_taken", "is_paid", "is_taken"] inlines = [ OrderingInline, ] admin.site.register(Item, ItemAdmin) admin.site.register(Order, OrderAdmin) admin.site.register(Client, ClientAdmin) admin.site.register(Ordering, OrderingAdmin)

注意:我建议您在发布SO之前检查Javadoc。这真的有帮助。

答案 1 :(得分:0)

java.time

现代方法使用了几年前取代了可怕的java.sql.Timestamp类的 java.time 类。具体来说,JDBC 4.2和更高版本为此支持OffsetDateTime

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

写入数据库。

myPreparedStatement.setObject( … , odt ) ;

检索。

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

enter image description here

DEFAULT CURRENT_TIMESTAMP

更好,自动化。在表的定义上使用DEFAULT,以在插入行时自动捕获当前时刻。有关标准SQL和MySQL语法的详细信息,请参见this Answer