I have several methods that do the same when interacting with a MySQL database, saving or loading a different type of parameter. I currently have a different method for each type. How can I combine these methods to support different types?
The following is an example of two methods that are very similar but use different types:
public static void saveLongArray(Connection con, int playerID, String tableName, String fieldName, long[] array, long[] originalArray) { try { for (int i = 0; i < array.length; i++) { // Check for change before running query if (array[i] != originalArray[i]) { if (array[i] != 0 && array[i] != -1) { PreparedStatement updateQuery = con.prepareStatement("REPLACE INTO `" + tableName + "` (`player_id`, `index`, `" + fieldName + "`) VALUES(?, ?, ?)"); updateQuery.setInt(1, playerID); updateQuery.setInt(2, i); updateQuery.setLong(3, array[i]); updateQuery.execute(); } else { PreparedStatement deleteQuery = con.prepareStatement("DELETE FROM `" + tableName + "` WHERE `player_id` = ? AND `index` = ?"); deleteQuery.setInt(1, playerID); deleteQuery.setInt(2, i); deleteQuery.execute(); } originalArray[i] = array[i]; } } } catch (SQLException ex) { Logger.getLogger(PlayerSaveHandler.class.getName()).log(Level.SEVERE, "SQL Exception while saving a long array!", ex); } } public static void saveIntArray(Connection con, int playerID, String tableName, String fieldName, int[] array, int[] originalArray) { try { for (int i = 0; i < array.length; i++) { // Check for change before running query if (array[i] != originalArray[i]) { if (array[i] != 0 && array[i] != -1) { PreparedStatement updateQuery = con.prepareStatement("REPLACE INTO `" + tableName + "` (`player_id`, `index`, `" + fieldName + "`) VALUES(?, ?, ?)"); updateQuery.setInt(1, playerID); updateQuery.setInt(2, i); updateQuery.setInt(3, array[i]); updateQuery.execute(); } else { PreparedStatement deleteQuery = con.prepareStatement("DELETE FROM `" + tableName + "` WHERE `player_id` = ? AND `index` = ?"); deleteQuery.setInt(1, playerID); deleteQuery.setInt(2, i); deleteQuery.execute(); } originalArray[i] = array[i]; } } } catch (SQLException ex) { Logger.getLogger(PlayerSaveHandler.class.getName()).log(Level.SEVERE, "SQL Exception while saving an int array!", ex); } }
Note that in this example, the types are numerical. In the case where the types are completely different (for example, int and String), what could I do to avoid methods that are close to duplication?