从数据库处理空字符串的最佳做法(在Java中) [英] Best practice for handling null strings from database (in Java)
问题描述
在我的数据库应用程序中,我有时必须处理数据库中的 null
字符串。在大多数情况下,这是好的,但是当它显示数据在一个形式的Swing组件 - 使用 JTextField
例如 - 不能处理空字符串。 ( .setText(null)
失败)
( EDIT: JTextField
实际接受 null
字符串,但问题仍然是所有其他意外 null
值可能会导致问题。)
空值没有特殊意义,它们可以(必须)被视为空字符串。
处理这个问题的最佳做法是什么?
/ $>之前添加一个try-catch处理程序介绍一个过滤所有 null
字符串的静态方法?
null
的值替换为空字符串?如果您使用任何ORM工具, Java bean你可以通过:
public void setFoo(String str){
this.foo = str! str:;
}
In my database application I sometimes have to deal with null
strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using JTextField
for example - cannot handle null strings. (.setText(null)
fails)
(EDIT: I just noticed that JTextField
actually accepts a null
string, but the question remains for all other cases where unexpected null
values can lead to problems.)
The null values have no special meaning, they can (must) be treated as empty strings.
What is the best practice to deal with this problem? Unfortunatly I cannot change the database.
- Checking every value if it is
null
before callingsetText()
? - Adding a try-catch handler to every
setText()
call? - Introducing a static method which filters all
null
strings? - Replace all
null
values to empty strings immediatly after reading from the database? - ... [your suggestions]
If you are using any ORM tool or somehow you map your DB fields to Java bean you can allways have:
public void setFoo(String str) { this.foo = str != null ? str : ""; }
这篇关于从数据库处理空字符串的最佳做法(在Java中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!