Java JDBC How to - Create triggers with multiple statements for mysql using jdbc driver








Question

We would like to know how to create triggers with multiple statements for mysql using jdbc driver.

Answer

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
/* w ww.  ja va2s  .  co m*/
public class Main {
  public static void main(String args[]) throws Exception {
    String connectionURL = "jdbc:mysql://localhost:3306/test";
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(connectionURL, "login", "password");
    Statement stmt = con.createStatement();
    stmt.execute("CREATE TRIGGER obs_update BEFORE UPDATE ON obs " //
        + "FOR EACH ROW "//
        + "BEGIN "//
        + "IF OLD.voided = 0 AND NEW.voided = 1 THEN "//
        + "   DELETE FROM emp WHERE id = OLD.obs_id; "//
        + "ELSE "//
        + "   UPDATE emp SET emp.revision_token = NOW() "//
        + "   WHERE NEW.id = emp.id; "//
        + "END IF; "//
        + "END;");
    con.close();
  }
}