PostgreSQL中的日期 [英] Date in postgresql
问题描述
如何将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();
请注意,日期
中有一个< a href = http://docs.oracle.com/javase/6/docs/api/java/sql/Date.html rel = noreferrer> 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.
这篇关于PostgreSQL中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!