从数据库处理空字符串的最佳做法(在Java中) [英] Best practice for handling null strings from database (in Java)

查看:82
本文介绍了从数据库处理空字符串的最佳做法(在Java中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库应用程序中,我有时必须处理数据库中的 null 字符串。在大多数情况下,这是好的,但是当它显示数据在一个形式的Swing组件 - 使用 JTextField 例如 - 不能处理空字符串。 ( .setText(null)失败)



EDIT: JTextField 实际接受 null 字符串,但问题仍然是所有其他意外 null 值可能会导致问题。)



空值没有特殊意义,它们可以(必须)被视为空字符串。



处理这个问题的最佳做法是什么?

/ $>
  • 之前添加一个try-catch处理程序介绍一个过滤所有 null 字符串的静态方法?

  • 从数据库读取后立即将所有 null 的值替换为空字符串?

  • ... [your建议]


  • 解决方案

    如果您使用任何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 calling setText()?
    • 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆