How to replace Null with empty string in Java insert prepared statement

Viewed 765

I have API response which I am using Java insert prepared statement to insert values in DB table. Few column values coming in from API response is- null. I want to replace this null value with empty string in my table. Can someone help with the piece of code.

Code snippet:

PreparedStatement stmt = conn.prepareStatement(query);
stmt.setDate(1, formatDate(obj.getString("term_dt")));
2 Answers

You can use the ternary operator to keep your code concise.

PreparedStatement stmt = conn.prepareStatement(query);
stmt.setDate(1, term_dt!=null ? formatDate(obj.getString("term_dt")) : "");

You can use Objects.toString(obj.getString("term_dt"), ""). It's a bit shorter than using a ternary operator.

Related