Create PostgreSQL trigger using JDBC

妖精的绣舞 提交于 2019-12-07 06:50:21

问题


I am trying to create a PostgreSQL trigger in a Play2.0 database evolution script. The sql code is relatively easy and runs fine in pgAdminIII:

CREATE OR REPLACE FUNCTION update_modified() RETURNS TRIGGER AS $$
  BEGIN
    NEW.modified = now();
    RETURN NEW;
  END;
$$ LANGUAGE 'plpgsql';

However, I get an error when running the evolution: ERROR: unterminated dollar-quoted string at or near "$$ BEGIN NEW.modified = now()". The SQL code seems to get truncated at the first semicolon encountered in the function. I am using the "9.1-901.jdbc4" JDBC driver for PostgreSQL.

Update:

The code in Evolutions.scala (line 219+) performs a simple split on the ;. Seems to be faulty in the framework itself:

// Execute script
s.sql.split(";").map(_.trim).foreach {
  case "" =>
  case statement => execute(statement)
}

Any solutions?


回答1:


You can try the following thing.

    String sql = "CREATE OR REPLACE FUNCTION update_modified() RETURNS TRIGGER AS $$ " +
            "BEGIN " +
                "NEW.modified = now(); " +
                "RETURN NEW; " +
                "END; " +
            "$$ LANGUAGE 'plpgsql';";
    DataSource ds = getDataSource();
    try {
        Connection conn = ds.getConnection();
        conn.setAutoCommit(true);
        Statement st = conn.createStatement();
        st.executeUpdate(sql);
        st.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

Hope this will work for you.



来源:https://stackoverflow.com/questions/10460542/create-postgresql-trigger-using-jdbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!