如何在Java插入预准备语句中将Null替换为空字符串

huangapple go评论68阅读模式
英文:

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

问题

我有一个API响应,我正在使用Java的插入预处理语句将值插入数据库表中。
从API响应中获取的部分列值是- null。我想将这个null值替换为表中的空字符串。有人可以帮忙提供一段代码。

代码片段:

PreparedStatement stmt = conn.prepareStatement(query);
stmt.setDate(1, formatDate(obj.getString("term_dt")));
英文:

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")));

答案1

得分: 1

可以使用三元运算符使您的代码更简洁。

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

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")) : "");

答案2

得分: 1

你可以使用 Objects.toString(obj.getString("term_dt"), "")。这比使用三元运算符要稍微更短一些。

英文:

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

huangapple
  • 本文由 发表于 2020年10月7日 22:30:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64246276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定