While Inserting Date into mysql , i have the following code
DateFormat format_date = new SimpleDateFormat("yy-mm-dd");
for (Stocker s : symbol_set) {
insert_stmt.setString(1, s.getName());
insert_stmt.setDouble(2, s.getPrice());
Date d = format_date.parse(s.getCurr_day());
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
insert_stmt.setDate(3, sqlDate);
insert_stmt.setString(4, s.getVolume());
insert_stmt.setDouble(5, s.getGainloss());
insert_stmt.addBatch();
}
insert_stmt.executeBatch();
Could you please let me know Is it possible to avoid creating java.sql.Date Object in For Loop or is this normal behaviour and cannot be skipped ??
It really depends on the implementation of PreparedStatement.setDate()
and addBatch()
.
If those methods clone all the relevant data appropriately, you could create a single instance of java.sql.Date
outside the loop, then call setTime
on that instance before calling setDate
.
However, that behaviour isn't documented, so I personally wouldn't want to rely on it. (This is one annoyance of mutable types - you can't easily guarantee the effect of mutation and reuse.) Basically it is normal behaviour unless you're really comfortable relying on a specific implementation detail - and that sounds like a really bad idea to me.
The good news is that each instance is going to be small... I'd be very surprised if this were really a performance issue compared with the fact that you're talking to a database.
See more on this question at Stackoverflow