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();
}
}
You shouldn’t do it like that at all!
Never, ever, construct SQL strings with their parameters in them. Instead, create a PreparedStatement and set the parameters on it. Like this:
Note that the
Datethere is ajava.sql.Date, which is a subclass of the normaljava.util.Datein 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 ajava.sql.Timestamp, which represents a moment in time.