Change String values in List<String> to java.sql.date values to insert into SQL DB

nice96 :

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!

Tim Biegeleisen :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12151&siteId=1