Search code examples
javams-accessms-access-2007jackcess

How to delete (DROP) an Access table using Jackcess


I am using Jackcess in my project to connect an MS Access database, but I couldn't find the method to delete a table.

How can I delete a table using Jackcess?

Database db = null;
try 
{
    db = Database.open(FileLocations.getCache());
    Table table = db.getTable("refNum");
    //table.delete(); //trying to achieve
}
catch (IOException ex) 
{
    Logger.getLogger(TheDatabase.class.getName()).log(Level.SEVERE, null, ex);
}
finally 
{
    try 
    {
        db.close();
    } 
    catch (IOException ex) 
    {
        Logger.getLogger(TheDatabase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Solution

  • The following code seems to do the trick:

    Database db = DatabaseBuilder.open(new File("C:/Users/Public/mdbTest.mdb")); 
    
    Table tbl = db.getSystemTable("MSysObjects");
    Cursor crsr = tbl.getDefaultCursor();
    
    Map<String, Object> findCriteria = new HashMap<String, Object>();
    findCriteria.put("Name", "refNum");
    findCriteria.put("Type", (short)1);
    
    String status = "";
    if (crsr.findFirstRow(findCriteria)) {
        tbl.deleteRow(crsr.getCurrentRow());
        status = "table dropped (row deleted from MSysObjects)";
    }
    else {
        status = "row not found in MSysObjects";
    }
    System.out.println(status);
    
    db.close();