3

I am trying to program a database application with java & PostgreSQL. I have some rows with date data type. But i cant add any entries to the database with this code :

Date aDate = null;
aDate.setYear(1990);
aDate.setDate(01);
aDate.setMonth(05);

preparedStatement prep = connection.prepareStatement("insert 
into exampletable values (?,?);");
prep.setDate(1, (java.sql.Date) aDate);
prep.setDate(2, (java.sql.Date) aDate);

How can i add a date in a postgreSQL row with queries in java?

Zzap
  • 174
  • 2
  • 3
  • 14
  • The `java.util` Date-Time API and their formatting API, `SimpleDateFormat` are outdated and error-prone. It is recommended to stop using them completely and switch to the [modern Date-Time API](https://www.oracle.com/technical-resources/articles/java/jf14-Date-Time.html). Check [this answer](https://stackoverflow.com/a/67752047/10819573) and [this answer](https://stackoverflow.com/a/67505173/10819573) to learn how to use `java.time` API with JDBC. – Arvind Kumar Avinash Jun 27 '21 at 13:34

1 Answers1

6

It's not clear whether or not this is your only problem, but this code is almost certainly not what you want:

Date aDate = null;
aDate.setYear(1990);
aDate.setDate(01);
aDate.setMonth(05);
  • It will throw a NullPointerException because you're trying to dereference null
  • You're then trying to set the year to 3890AD (java.util.Date is 1900-based for years)
  • You're then setting the month to June. If you thought you were setting the month to May, think again - Date is 0-based for months
  • All the methods you're using are deprecated - that should raise a big warning light for you
  • You're then trying to cast aDate to java.sql.Date but there's no sign that it is a java.sql.Date

I would suggest:

  • Either use Joda Time as a far better date/time API, or java.util.Calendar
  • Make sure you actually create an instance before you set values
  • Probably create a new java.sql.Date later on.

For example:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 1990);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, 4); // Assuming you wanted May 1st

java.sql.Date date = new java.sql.Date(calendar.getTime().getTime());

// Ideally specify the columns here as well...
PreparedStatement prep = connection.prepareStatement(
    "insert into exampletable values (?,?)");
prep.setDate(1, date);
prep.setDate(2, date);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @RafaelWerlang: Your edit suggestion is incorrect. `Calendar.getTime()` returns a `java.util.Date`; `java.util.Date.getTime()` returns a `long`. There's a `java.sql.Date(long)` constructor, but no `java.sql.Date(java.util.Date)` constructor. – Jon Skeet Jul 19 '17 at 20:08