使用Java Servlet检查数据库中的重复条目时更新记录

时间:2018-05-15 16:00:17

标签: java sql-server

我正在尝试更新记录并检查其他行中的重复项。以下内容适用于Insert,因为它是一个新条目,但不适用于更新。更新表单中预先填充的现有值,如果单击更新而不更改任何内容或更新其他字段,则显示重复条目的错误。此外,更新不应检查重复的当前行。我该如何解决这个

public boolean isFilePositionExist( int filePosition)     throws SQLException {
    boolean isExist = false;
    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    try {
        conn = DataSource.getDBConnection();
        st = conn.createStatement();
        rs = st.executeQuery("SELECT COUNT('File_Position') AS 'Count' FROM FIELD_MAPPING WHERE File_Position = '"+filePosition+"' AND Match_Type_Id = '"
                + matchTypeId + "'");
        if (rs.next() && rs.getInt("Count") > 0) {
            isExist = true;
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw e;
    } finally {
        DataSource.close(st);
        DataSource.close(rs);
        DataSource.close(conn);
    }
    return isExist;
}

  if( fieldMappingDAO.isFilePositionExist( filePosition)) {
            sb.append("File Position Already Exists.");
            isError = true;
        }

public void editMapping(fieldsMapping fieldsMapping, int previousVersion, String previousFieldLabel) throws SQLException {
    Connection conn = null;
    PreparedStatement pst = null;
    try {
        conn = DataSource.getDBConnection();
        String sql=("UPDATE FIELD_MAPPING SET Field_Label = ?,Version = ?,Index_Field_Name = ?,Stage_Field_Name = ?,File_Position = Display_Order = ?,Min_Template_Version = ?,Last_Update_Date = ? where Match_Type_Id = ? AND Field_Label = ? AND Version = ?");
        pst = conn.prepareStatement(sql);
        pst.setString(1, fieldsMapping.getFieldLabel());
        pst.setInt(2, fieldsMapping.getVersion());
        pst.setString(3, fieldsMapping.getIndexFieldName());
        pst.setString(4, fieldsMapping.getStageFieldName());
        pst.setInt(5, fieldsMapping.getFilePosition());
        pst.setInt(9, fieldsMapping.getDisplayOrder());
        pst.setString(10, fieldsMapping.getMinTemplateVersi());
        pst.setTimestamp(11, new Timestamp  (System.currentTimeMillis())); 
        pst.setString(12, fieldsMapping.getMatchTypeId());
        pst.setString(13, previousFieldLabel);
        pst.setInt(14, previousVersion);
        int a = pst.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
        throw e;
    } finally {
        DataSource.close(pst);
        DataSource.close(conn);
    }
}

0 个答案:

没有答案