2

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")));
3
  • 1
    something like this: v==null ? "" : v Commented Oct 7, 2020 at 14:42
  • 3
    Does it make sense to use "" when calling formatDate? Possibly you should call PreparedStatement's method setNull or provide appropriate default value? Commented Oct 7, 2020 at 15:01
  • Thanks Guys, I tried with if statement and it worked :if((obj.getString("term_dt"))!="null"){ stmt.setDate(1, formatDate(obj.getString("term_dt"))); } else{ stmt.setString(1,""); } Commented Oct 7, 2020 at 19:50

2 Answers 2

1

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

Comments

1

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

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.