How to truncate all tables using a SQL query

104 views Asked by At

I am trying to run the sql script from my java code to truncate all the tables from particular database. I am using apache-ibatis-3.5.13 which have a script runner class. It seems to be not working with PLSQL script. Here is the script:

-- @DELIMITER $
do
$$
DECLARE row RECORD;
BEGIN
  FOR row IN SELECT table_name
    FROM information_schema.tables
    WHERE table_type='BASE TABLE'
    AND table_schema='public'
    AND table_name NOT IN ('admins', 'admin_roles')
    AND table_catalog='my_db' 
  LOOP 
    EXECUTE format('TRUNCATE TABLE %I CONTINUE IDENTITY RESTRICT;',row.table_name);
  END LOOP;
END;
$$
-- @DELIMITER $

My java code is like that:

public static void resetDB(SqlConnection conn, URL url) throws FileNotFoundException, SQLException {
        try {
            if (conn.isConnected()) {
                PrintWriter logWriter = new PrintWriter(System.out);
            PrintWriter errorLogWriter = new PrintWriter(System.err);

            ScriptRunner sr = new ScriptRunner(conn.getConnection());
            sr.setStopOnError(true);
            sr.setDelimiter("]");
            sr.setLogWriter(logWriter);
            sr.setErrorLogWriter(errorLogWriter);

            Reader reader = new BufferedReader(new FileReader(new File(url.getFile())));
            // Running the script
            sr.setSendFullScript(true);
            sr.runScript(reader);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

There is no exception or error is showing when i run this script and data is still in the tables. I have another solution where i can call the select query from information_schema.tables and then run the truncate query from java but not liking the idea and really wants to do it via sql script. Any one have idea about it?

0

There are 0 answers