Hi.
Im trying to create a java class that deletes all data in a db. When its done Id like only empty tables. The problem is that I dont know anything about the tables and the structure.
Ive got two methods for this, the firs one, getTabs(), returns all tables in my db. The second one does DELETE FROM <table>. This works as long as there is no connection to other tables.
But if one of the records is used in another table as FOREIGN KEY, I get an : violates foreign key constraint message.
This can be fixed doing DELETE FROM <table> in a correct order. But I need to figure out a way to find the correct order.
Any one who has any ideas?
[code]
public List<String> getTabs() {
List<String> tabeller = new ArrayList<String>();
try {
Statement st = conn.createStatement();
DatabaseMetaData dmd = conn.getMetaData();
String types[] = {"TABLE"};
ResultSet rs = dmd.getTables(null, null, null, types);
while(rs.next()) {
tabeller.add(rs.getString(
"TABLE_NAM
E"));
}
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return tabeller;
}
public void emptyTabs(List<String> tabs) {
Statement st;
try {
st = conn.createStatement();
for(String a : tabs) {
st.execute("DELETE FROM " + a + ";");
}
st.close();
}catch (SQLException ex) {
ex.printStackTrace();
}
}
[/code]
Start Free Trial