从我的Java代码执行sql文件名sample_script.sql
时出现错误。这是一个Spring应用程序,因为我想自动运行脚本,因此我试图通过Java类ScriptRunner
运行脚本。
sample_script.sql:
CREATE OR REPLACE FUNCTION core.getValue (id bigint, field varchar)
RETURNS text
AS $$
DECLARE json_object json;
DECLARE item json;
DECLARE val text;
BEGIN
SELECT E.json::json into json_object from customer E where E.id = id;
FOR item IN SELECT * FROM json_array_elements((json_object->>'name')::json)
LOOP
IF (item->>'data') = field
THEN
val = (item->>'values')::json->>0;
END IF;
END LOOP;
return val;
END;
$$ LANGUAGE 'plpgsql';
它从PGAdmin运行正常,但是当我从spring项目中运行该文件时,就像下面的一样,它给出了错误。
Java代码段:
ScriptRunner sr = new ScriptRunner(con, false, false);
Reader reader = new BufferedReader(new FileReader("sample_script.sql"));
sr.runScript(reader);
错误日志:
Error executing: CREATE OR REPLACE FUNCTION core.getValue (id bigint, field varchar) RETURNS text AS $$ DECLARE json_object json
org.postgresql.util.PSQLException: ERROR: unterminated dollar-quoted string at or near "$$ DECLARE json_object json "
Position: 91
在执行脚本时,它也会从脚本中删除;
,如下所示:
CREATE OR REPLACE FUNCTION core.getValue (id bigint, field varchar) RETURNS text AS $$ DECLARE json_object json
DECLARE item json
DECLARE val text
BEGIN SELECT E.json::json into json_object from customer E where E.id = id
FOR item IN SELECT * FROM json_array_elements((json_object->>'name')::json) LOOP IF (item->>'data') = field THEN val = (item->>'values')::json->>0
END IF
END LOOP
return val
END
$$ LANGUAGE 'plpgsql'
任何人都可以解释为什么会发生这种情况以及如何解决吗?
注意:我见过this,但对这个问题没有帮助。
答案 0 :(得分:0)
使用Statement.execute()代替ScriptRunner
。
更新的Java代码段:
Connection con = sessionFactory.getSessionFactoryOptions().getServiceRegistry().getService(ConnectionProvider.class).getConnection();
BufferedReader in = new BufferedReader(new FileReader("sample_script.sql"));
LineNumberReader fileReader = new LineNumberReader(in);
String query = ScriptUtils.readScript(fileReader, ScriptUtils.DEFAULT_COMMENT_PREFIX, ScriptUtils.DEFAULT_STATEMENT_SEPARATOR);
Statement stmt = null;
stmt = con.createStatement();
stmt.execute(query);