如何检查是否存在两个值?

时间:2017-12-16 13:08:05

标签: java postgresql jdbc

我正在尝试实现一个程序(用Java)来检查数据库中是否存在两个值(PostgreSQL)。这是我的问题:

我有一个外部文档,Java读取这些值:

#  letter_id, child_id, toy_id
18,1,2
18,1,3
18,2,1

第一行将此值放入数据库中,原因如下:我的数据库中不存在字母,然后将letter_idchild_id插入LETTER(这是一个表格)并插入WISHED TOY(这是一个表)。

出于这个原因,第二行插入到数据库中:字母存在且child_id相同,但toy_id不同。然后,将值更新为LETTER并将letter_idtoy_id插入WISHED TOY

第三行将失败,原因如下:字母存在且child_id不同,这是不可能的,只有一个孩子可以写1个字母。无法添加此案例,因为两个孩子不能写同一个字母。

我有这个我想要使用的功能:

private Integer getLetterId(List<String> row)
{
    String integer;
    String[] rowArray = (String[]) row.toArray(new String[0]);
    integer = rowArray[0]; //Letter_Id
    return (null != integer) ? Integer.valueOf(integer) : null;
}

private Integer getChildId(List<String> row)
{
    String integer;
    String[] rowArray = (String[]) row.toArray(new String[0]);
    integer = rowArray[1]; //Child_Id
    return (null != integer) ? Integer.valueOf(integer) : null;
}

我的想法是:

If letter exists {
    If letter exists for this child {
        UPDATE LETTER
        INSERT WISHED
    }
    ELSE {
        //this case  will be return an error because letter not coincide with child
    }
Else {
   Insert Letter
   Insert Wished
}
}

希望是另一个表格,如果存在或不存在字母,则放置letter和toy_id。

我理解如何实现第一个'if':( if(rs.next()))

但我觉得我对'if'有问题:if(childId == row.getChildId(1))

那么,我该怎么办呢?有什么帮助吗?

编辑:对不起,我不知道我做错了什么:

    if (conn != null) {

        PreparedStatement selectPS = null;
        ResultSet rs = null;
        Integer childId;
        Integer letterId;

        try {
            String selectSql = "SELECT child_id FROM letter WHERE letter_id = ?";
            selectPS = conn.prepareStatement(selectSql);

            for (List<String> row : fileContents) {
            // TODO Update or insert record from PLAYER for every row in file

                selectPS.clearParameters();
                setSelectPreparedStatement (selectPS,row);
                rs = selectPS.executeQuery();
                childId = rs.getInt("child_id");
                letterId = rs.getInt("letter_id");

                if (rs.next())
                {
                    if (childId == getChildId (row))
                    {
                        System.out.println("Updating");
                    }
                    if (childId != getChildId (row) && letterId == getLetterId(row))
                    {
                        System.out.println("This letter are used by other child");
                    }

                }
                else
                {
                    System.out.println("Inserting values to letter and wished");
                }
          }
     }
}

我收到此错误:

  

错误:执行
  SQL ResultSet未正确定位,可能需要调用next。

1 个答案:

答案 0 :(得分:0)

rs = selectPS.executeQuery();之后你必须检查是否有任何行,这意味着应该运行rs.next()。我的意思是你必须搬家 childId = rs.getInt("child_id"); letterId = rs.getInt("letter_id"); if(rs.next()){

之后
相关问题