postgressql中的日期 [英] Date in postgressql

查看:249
本文介绍了postgressql中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将java Date对象插入到Postgresql DATE单元格中?

How to insert java Date object into Postgresql DATE cell?

当我以这种方式执行时,这是错误的:

When i do it my way, it's wrong:

Calendar date = Calendar.getInstance(); // wrong
Date date = new Date(); // wrong         

String addRecord = "INSERT INTO " + GlobalFields.PACJENCI_TABLE +
                                "VALUES (" + date + ");";
stat.executeUpdate(addRecord)

我没有更多的想法...

I have no more ideas...

PS:

public static void CreatePacjenciTable()
    {
        try
        {
            Connection conn = DataBase.Connect();

            try
            {
                Statement stat = conn.createStatement();

                String createTable = "CREATE TABLE " + GlobalFields.PACJENCI_TABLE 
                    + "(dataUrodzenia DATE);";

                stat.executeUpdate(createTable);
            }
            finally
            {
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        } 
    } 


推荐答案

你不应该这样做!

永远不会用它们的参数构造SQL字符串。而是创建 PreparedStatement 并设置参数在上面。像这样:

Never, ever, construct SQL strings with their parameters in them. Instead, create a PreparedStatement and set the parameters on it. Like this:

    String addRecord = "INSERT INTO " + GlobalFields.PACJENCI_TABLE + "VALUES (?);";
    PreparedStatement stmt = conn.prepareStatement(addRecord);
    stmt.setDate(1, new Date(System.currentTimeMillis()));
    stmt.executeUpdate();

请注意, Date a href =http://docs.oracle.com/javase/6/docs/api/java/sql/Date.html =nofollow> java.sql.Date ,它是正常的 java.util.Date 的子类,其中的时间始终是UTC的午夜;它用于表示实际的日期,而不是时间。您也可以使用 java。 sql.Timestamp ,代表了一段时间。

Note that the Date there is a java.sql.Date, which is a subclass of the normal java.util.Date in which the time of day is always midnight UTC; it is used to represent an actual date, not a moment in time. You can alternatively use a java.sql.Timestamp, which represents a moment in time.

这篇关于postgressql中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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