简体   繁体   中英

How to get all trigger names from a database using Java JDBC?

I'd like to retrieve all trigger names from an Oracle database schema.

I use getFunctions to retrieve all functions but i can't find another one for the triggers.

DatabaseMetaData dbmd;
ResultSet result = dbmd.getFunctions(null, Ousername, null);

You can do it using metadata.

DatabaseMetaData dbmd = dbConnection.getMetaData(); 
ResultSet result = dbmd.getTables("%", Ousername, "%", new String[]{ "TRIGGER" });
while (result.next()) {
     result.getString("TABLE_NAME")
}

The JDBC API does not provide a standard way to retrieve trigger information from the DatabaseMetaData. In fact, the word "trigger" does not even appear in the Javadoc. The accepted answer may work for Oracle, but it is not documented, and it certainly does not work for other databases like HSQL and PostgreSQL.

The only way, at this time, to retrieve trigger information without finding some undocumented backdoor hack in the JDBC driver is to issue database specific queries.

I have found another way to get all trigger via PreparedStatement:

try {
    System.out.println("\n******* Table Name: "+ tableName);    
    String selectQuery = "SELECT TRIGGER_NAME FROM ALL_TRIGGERS WHERE TABLE_NAME = ?";
    PreparedStatement statement = DataSource.getConnection().prepareStatement(selectQuery); 
    statement.setString(1, tableName.toUpperCase());
    ResultSet result = statement.executeQuery();

    System.out.println("Triggers: ");
    while (result.next()) {
        String triggerName = result.getString("TRIGGER_NAME");
        System.out.println(triggerName);
    }
} catch (SQLException e) {
    e.printStackTrace();
}

Just hint for MySQL users: if you want to retrieve all triggers from MySQL database there is table TRIGGERS in INFORMATION_SCHEMA with all info about database triggers:

SELECT * FROM INFORMATION_SCHEMA.TRIGGERS

Similar is for routines (Functions and Procedures)

SELECT * FROM INFORMATION_SCHEMA.ROUTINES

Unfortunately triggers are not well supported in JDBC MetaData.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM