1

我尝试运行一个简单的类来从 Java 代码中调用 TRIGGER,我使用了 H2 DB,你能帮帮我吗?这是我的简单代码(如 H2 中的示例代码):

public class TriggerTest {

public static void main(String[] args) throws Exception {
    System.out.println(TriggerTest.MyTrigger.class.getName());
    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/chap1", "sa", "sa");
    Statement stat = conn.createStatement();
    stat.execute("Drop Table if exists INVOICE");
    stat.execute("Drop Table if exists INVOICE_SUM");
    stat.execute("CREATE TABLE INVOICE(ID INT PRIMARY KEY, AMOUNT DECIMAL)");
    stat.execute("CREATE TABLE INVOICE_SUM(AMOUNT DECIMAL)");
    stat.execute("INSERT INTO INVOICE_SUM VALUES(0.0)");
    stat.execute("CREATE TRIGGER INV_INS AFTER INSERT ON INVOICE FOR EACH ROW CALL \""+TriggerTest.MyTrigger.class.getName()+"\"");
    stat.execute("CREATE TRIGGER INV_UPD AFTER UPDATE ON INVOICE FOR EACH ROW CALL \""+TriggerTest.MyTrigger.class.getName()+"\"");
    stat.execute("CREATE TRIGGER INV_DEL AFTER DELETE ON INVOICE FOR EACH ROW CALL  \""+TriggerTest.MyTrigger.class.getName()+"\"");

    stat.execute("INSERT INTO INVOICE VALUES(1, 10.0)");
    stat.execute("INSERT INTO INVOICE VALUES(2, 19.95)");
    stat.execute("UPDATE INVOICE SET AMOUNT=20.0 WHERE ID=2");
    stat.execute("DELETE FROM INVOICE WHERE ID=1");

    ResultSet rs;
    rs = stat.executeQuery("SELECT AMOUNT FROM INVOICE_SUM");
    rs.next();
    System.out.println("The sum is " + rs.getBigDecimal(1));
    conn.close();
}

public static class MyTrigger implements Trigger {

    public void init(Connection conn, String schemaName, String triggerName, String tableName, boolean before, int type) {
        // Initializing trigger
    }

    public void fire(Connection conn,
            Object[] oldRow, Object[] newRow)
            throws SQLException {
        BigDecimal diff = null;
        if (newRow != null) {
            diff = (BigDecimal) newRow[1];
        }
        if (oldRow != null) {
            BigDecimal m = (BigDecimal) oldRow[1];
            diff = diff == null ? m.negate() : diff.subtract(m);
        }
        PreparedStatement prep = conn.prepareStatement(
                "UPDATE INVOICE_SUM SET AMOUNT=AMOUNT+?");
        prep.setBigDecimal(1, diff);
        prep.execute();
    }

}

和错误:线程“main”中的异常 org.h2.jdbc.JdbcSQLException:创建或初始化触发器“INV_INS”对象时出错,类“vn.com.khangpn.core.trigger.TriggerTest$MyTrigger”,原因:“org.h2 .message.DbException:类“”vn.com.khangpn.core.trigger.TriggerTest$MyTrigger“”未找到[90086-169]”;有关详细信息,请参阅根本原因;SQL 语句:

4

1 回答 1