Search code examples
javadatabasercpjackcess

Delete specific rows from an Access table using Jackcess


I am using the Jackcess API with an Access database. I open the database and get a specific table. How can I get the data (rows) from this table which matches a list of ids?

For example get all the rows from the table where id is in List.

 private List<Component> disabledComponentsIds;
 private Database db = null;

 db = Database.open(new File(target), false, false);

 Table table = db.getTable("t_object");
        Table packages = db.getTable("t_package");
        for(Map<String, Object> r : table){
            if(disabledComponentsIds.contains(r.get("ea_guid"))){
                r.get("package_id");
                //Delete row from t_package table where id  = r.get("package_id")
            }
        }

In this particular case I want to delete the rows.


Solution

  • Given a table named "t_object" ...

    object_id  object_name
    ---------  -----------
            1  alpha      
            2  bravo      
            3  charlie    
            4  delta      
            5  echo       
    

    ... where "object_id" is the primary key, you could delete specific rows like so:

    // test data
    ArrayList<Integer> enabledComponentsIds = new ArrayList<>();
    enabledComponentsIds.add(2);
    enabledComponentsIds.add(3);
    
    String dbFileSpec = "C:/Users/Public/jackcessTest.mdb";
    try (Database db = DatabaseBuilder.open(new File(dbFileSpec))) {
        Table t = db.getTable("t_object");
        for (int id : enabledComponentsIds) {
            Row r = CursorBuilder.findRowByPrimaryKey(t, id);
            if (r != null) {
                t.deleteRow(r);
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    

    That will delete the rows where "object_id" is 2 or 3.

    Edit:

    If the column is not indexed then you'll have to iterate through each row (as Kayaman suggested) and see if its column value is contained in the list:

    // test data
    ArrayList<Integer> enabledComponentsIds = new ArrayList<>();
    enabledComponentsIds.add(2);
    enabledComponentsIds.add(3);
    
    String dbFileSpec = "C:/Users/Public/jackcessTest.mdb";
    try (Database db = DatabaseBuilder.open(new File(dbFileSpec))) {
        Table t = db.getTable("t_object");
        for (Row r : t) {
            if (enabledComponentsIds.contains(r.getInt("object_id"))) {
                t.deleteRow(r);
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }