如何在插入之前检查数据库是否有重复项?

时间:2017-03-15 10:47:18

标签: java mysql sql

我想在插入数据库之前检查数据库是否有重复项。当plateNo,driverID和resDate匹配时,它仅被视为重复。

以下是我如何获取将插入数据库的数据

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        String client = (String) clientCmb.getSelectedItem();
        String[] cparts = client.split("-");
        String cpart = cparts[0];

        String driver = (String) driverCmb.getSelectedItem();
        String[] dparts = driver.split("-");
        String dpart = dparts[0];

        String van = (String) vanCmb.getSelectedItem();

        java.util.Date oDate = jXDatePicker2.getDate();
        DateFormat oDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = oDateFormat.format(oDate);
        model2.addRow(cpart, dpart, van, date);


    } 

这是我的addRow方法的代码

public void addRow(String client, String driver, String van, String res){

        try {
            String sqlRes =  "Select * from reservation";
            rs = st.executeQuery(sqlRes);
            rs.moveToInsertRow();

            rs.updateString("clientID", client);
            rs.updateString("plateNo", van);
            rs.updateString("driverID", driver);
            rs.updateString("resDate", res);
            rs.insertRow();
            rs.moveToCurrentRow();
            rs = st.executeQuery(sqlRes);
            this.fireTableDataChanged();
        } catch (SQLException ex) {
            Logger.getLogger(MyModel2.class.getName()).log(Level.SEVERE, null, ex);
        }

2 个答案:

答案 0 :(得分:2)

让数据库为您完成工作。定义唯一索引/约束,指定这三个值在表中是唯一的:

Protected Sub txtFiltrarNomeUtente_TextChanged(sender As Object, e As EventArgs) Handles txtFiltrarNomeUtente.TextChanged
  (code...)
End Sub

如果您尝试插入副本 - 或执行导致重复的create unique index unq_reservation_3 on reservation(plateNo, driverID, resDate); ,则数据库将返回错误。你只需要抓住错误。

答案 1 :(得分:1)

使用MERGE语句:T-SQLORACLE,或用于MySQL:

PreparedStatement p = con.prepareStatement("
    INSERT INTO reservation tgt (clientID, plateNo, driverID, resDate)
    SELECT (? As clientID, ? As plateNo, ? As driverID, ? As resDate)
    FROM DUAL ins
    LEFT JOIN reservation ref
        ON  ref.resDate = ins.resDate
       AND (ref.plateNo = ins.plateNo OR ref.driverID = ins.driverID)
    WHERE ref.clientID IS NULL;
");
p.setString(1, client);
p.setString(2, van);
p.setString(3, driver);
p.setString(4, res);
return p.executeUpdate(); /* 1 - Success | 0 - Ignored Duplicate */