Java SQL插入,其中2个相同的值不存在

时间:2015-12-18 20:51:19

标签: java mysql

在我的java应用程序中,我试图在我的数据库中插入一个“玩家回合”,其中同一玩家不能再次在同一个“holeNumber”。

我的PlayerRound表

enter image description here

目前,我有这个,最后一行只是伪代码,以显示我正在尝试做的事情。

"insert into PlayerRound(playerID, roundID, holeNumber, holeScore) "
    + "select (select playerID from Player where playerID = ?),"
    + "(select roundID from Round where roundID = ?),"
    + "(select holeID from HoleDetails where holeID = ?),? "
    + "WHERE playerID and holeNumber dont already exist in the table"; //correction in sql?

选择只是检查从表中检查外键。

我无法理解的部分是最后一行。我不知道“WHERE”语句应该去哪里以及它应该如何检查当前表是否已经在先前插入的相同holeNumber中具有相同的playerID。

当前插入声明:

"insert into PlayerRound(playerID, roundID, holeNumber, holeScore) "
    + "select (select playerID from Player where playerID = ?),"
    + "(select roundID from Round where roundID = ?),"
    + "(select holeID from HoleDetails where holeID = ?), ?"

enter image description here

try {
        PreparedStatement pdt = conn.prepareStatement(sql1);
        pdt.setString(1, playerID);
        pdt.setString(2, roundID);
        pdt.setString(3, holeNumber.getText());
        pdt.setString(4, holeScore.getText());



        // put the rest of the code
        int n1 = pdt.executeUpdate();
        if (n1 > 0) {
            JOptionPane.showMessageDialog(null, "Inserted into PlayerRound Successfully!");

        }
    } catch (SQLException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Insert into PlayerRound failed!");
    }

1 个答案:

答案 0 :(得分:0)

CREATE UNIQUE INDEX ix_player_round_hole
  ON PlayerRound (playerID, roundID, holeNumber);

将告诉数据库确保给定玩家在给定回合期间可以访问给定的洞不超过一次,但是可以访问给定回合中的多个(不同)洞并且在不同回合期间访问相同的洞。然后,您可以将查询简化为

INSERT INTO PlayerRound (playerID, roundID, holeNumber, holeScore)
  VALUES (?, ?, ?, ?)

如果您尝试违反此约束或链接到其他表的FK约束,则JDBC将抛出可捕获的异常。