Question

How do i delete all the tables in the schema on Apache Derby DB using JDBC?

Was it helpful?

Solution

For actual code that does this, check CleanDatabaseTestSetup.java in the Derby test suite section of the Derby distribution.

OTHER TIPS

Thanks are due to the blog:

Step 1:

Run the SQL statement, but don't forget to replace the schema name 'APP' with your your schema name in the 2 occurrences below:

SELECT
'ALTER TABLE '||S.SCHEMANAME||'.'||T.TABLENAME||' DROP CONSTRAINT '||C.CONSTRAINTNAME||';'
FROM
    SYS.SYSCONSTRAINTS C,
    SYS.SYSSCHEMAS S,
    SYS.SYSTABLES T
WHERE
    C.SCHEMAID = S.SCHEMAID
AND
    C.TABLEID = T.TABLEID
AND
S.SCHEMANAME = 'APP'
UNION
SELECT 'DROP TABLE ' || schemaname ||'.' || tablename || ';'
FROM SYS.SYSTABLES
INNER JOIN SYS.SYSSCHEMAS ON SYS.SYSTABLES.SCHEMAID = SYS.SYSSCHEMAS.SCHEMAID
where schemaname='APP';

Step 2:

The result of the above execution is a set of SQL statements, copy them to the SQL editor, execute them, then the constraints and the tables are dropped.

Do a little method in java in which you execute a

DROP TABLE [tablename]

tablename is passed by parameter.

And another method in which you loop over a record set formed by the query

SELECT tablename FROM SYSTABLES

calling the first method.

Derby latest documentation

I think most db providers don't allow DROP TABLE * (or similar).

I think the best way would be to SHOW TABLES and then go through each deleting in a loop via a resultset.

HTH.

JDBC allows you to solve your task in a database agnostic way:

  1. Open the connection
  2. Grab the DatabaseMetaData
  3. Use it to list all tables in your database JavaDoc
  4. Iterate over the resultset and fire the DROP TABLE for each table
  1. you must generate schema and table name from Derby DB system catalog.
  2. Order all tables by relation.
  3. Generate java statement for drop all tables
  4. Use autoCommit() method and set this method to false. for manual commit or rollback transactions when got errors.
  5. Run you java process. Good Luck.

A simpler solution is to use JDBC to run "drop database foo" then "create database foo". However, this will cause all objects in the DB to be deleted (i.e. not just tables).

If you're working from the command prompt rather than through JDBC, this should get you started.

SELECT 'DROP TABLE ' || schemaname ||'.' || tablename || ';'
FROM SYS.SYSTABLES
INNER JOIN SYS.SYSSCHEMAS ON SYS.SYSTABLES.SCHEMAID = SYS.SYSSCHEMAS.SCHEMAID
;

A simple solution is to do right click -> disconnect then delete the folder containing your database and reconnect it.

Download Squirrel SQL from http://squirrel-sql.sourceforge.net/

Connect to the database.

Expand the TABLE node.

Select the tables that you want to drop.

Right click and select -> Scripts -> Drop table scripts

Run the generated queries

You can even select delete records to empty the selected tables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top