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?

1
  • 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. Check this answer and this answer to learn how to use java.time API with JDBC. Commented Jun 27, 2021 at 13:34

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.