1

I have a List of String values that contains the date in the format "yyyy-MM-dd".

I am currently trying to iterate through the list to add the individual values to the DB.

How do I convert the individual String values in the String List to java.sql.Date values in order for them to match the data type contained in the database?

Below is an example of the code I am using:

    List<String> accessedDate = usageEvent.getDate();
    List<Integer> totlUsageHits = usageEvent.getHits();
    List<Integer> totlUsageVisitors = usageEvent.getVisitors(); 

    Iterator<String> accessDate = accessedDate.iterator();
    Iterator<Integer> hits = totlUsageHits.iterator();
    Iterator<Integer> visitors = totlUsageVisitors.iterator();

    while (accessDate.hasNext() && hits.hasNext() && visitors.hasNext()) {
            insert.setDate(1, accessDate.next());
            insert.setInt(2, hits.next());
            insert.setInt(3, visitors.next());
            insert.addBatch();
    }

Where I have insert.setDate(1, accessDate.next());, I want to change the String values from this list to java.sql.Date values.

Any help would be appreciated!

3
  • Duplicate: stackoverflow.com/questions/9624777/… Commented Feb 24, 2020 at 16:17
  • your question is "How to convert String to java.sql.date" :) Commented Feb 24, 2020 at 16:17
  • How do I implement this is relation to my above code? Commented Feb 24, 2020 at 16:18

1 Answer 1

5

The JDBC driver serves as a bridge adapter between the types/data in your Java code, and the actual statement which will run on your SQL database. One approach here would be to convert your text Java dates to LocalDate, and then bind them to the statement as objects:

while (accessDate.hasNext() && hits.hasNext() && visitors.hasNext()) {
    String date = accessDate.next();
    LocalDate localDate = LocalDate.parse(date);
    insert.setObject(1, localDate);
    insert.setInt(2, hits.next());
    insert.setInt(3, visitors.next());
    insert.addBatch();
}

A JDBC 4.2 driver should know how to deal with a Java LocalDate object. You might have actually been OK with the text dates, because there are in an ISO format, but it is better to avoid working with string dates, both in Java and SQL.

Sign up to request clarification or add additional context in comments.

Comments

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.