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

问题描述

在我的数据库应用程序中,我有时必须处理数据库中的介绍一个过滤所有 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中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-05 17:08