比较从java和sql中的数据库获得的值

时间:2014-10-19 10:20:46

标签: java sql

我试图比较我从我的数据库获得的两个值,如果BOTH值为null或者我的数据库中不存在,则返回true。我已经尝试在netbeans中调试它将从rs.getString跳转(“post_id”)。equals(“”);返回喜欢;它不会读取下一个rs.getString和if语句。顺便说一句,这是我的代码

public boolean likedPost()
{
    String thePostID = POSTID();
    String likerName = objInfo.name;
    boolean liked = true;

    try
    {
        String sql = "select * from Like where post_id=? and people_who_like=?";
        pst = conn.prepareStatement(sql);
        pst.setString(1,thePostID);
        pst.setString(2,likerName);
        rs = pst.executeQuery();
        boolean comparePostID = rs.getString("post_id").equals("");
        boolean compareLiker = rs.getString("people_who_like").equals("");

        if(liked == (comparePostID && compareLiker))
            liked = true;
        else
            liked = false;
    }

    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null,e);
    }

    return liked;
}

2 个答案:

答案 0 :(得分:1)

使用 StringUtils (org.apache.commons.lang.StringUtils)比较字符串。 StringUtils类的isEmpty()方法在内部检查给定的String是否为空或是否为空。

String postId = rs.getString("post_id")
String liker =  rs.getString("people_who_like");

if(StringUtils.isEmpty(postId) && StringUtils.isEmpty(postId)) {
    liked = true;
} else {
    liked = false;
}

编辑:您可以简单地将事情简化为

if (postId!= null && liker!= null && !postId.equals("") && !liker.equals("")) {

            liked = true;

        } else {

            liked = false;
        }

答案 1 :(得分:0)

String comparePostID = rs.getString("post_id");
String compareLiker = rs.getString("people_who_like");

if(comparePostID && comparePostID && !comparePostID.equals("") && !compareLiker.equals(""))
    liked = true;
else
    liked = false;