如何在 Java 中进行这样的查询并获取结果:
SELECT filedata.num,st_area(ST_Difference(ST_TRANSFORM(filedata.the_geom,70066),filedata_temp.the_geom))
FROM filedata, filedata_temp
Where filedata.num=filedata_temp.num
或者,我认为如果我根据这个查询在 Postgres 中创建过程会更好。
CREATE OR REPLACE FUNCTION get_geom_difference()
RETURNS void AS
$$
BEGIN
SELECT filedata.num,st_area(ST_Difference(ST_TRANSFORM(filedata.the_geom,70066),filedata_temp.the_geom))
FROM filedata, filedata_temp
Where filedata.num=filedata_temp.num
end;
$$
LANGUAGE 'plpgsql'
并调用它
Connection ce_proc= null;
ce_proc = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgis","postgres","123456");
java.sql.CallableStatement proc = ce_proc.prepareCall("{get_geom_difference()}");
proc.execute();
proc.close();
ce_proc.close();
但是如何在 Java 中从这个过程中获取结果呢?
更新
我试过这个SP
DROP FUNCTION get_geom_difference();
CREATE OR REPLACE FUNCTION get_geom_difference()
RETURNS integer AS
$$
DECLARE
tt integer;
BEGIN
SELECT filedata.num INTO tt
FROM filedata
Where filedata.num=1;
RETURN tt;
END;
$$
LANGUAGE 'plpgsql'
然后打电话
Class.forName("org.postgresql.Driver");
Connection connect= null;
connect = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgis","postgres","123456");
java.sql.CallableStatement proc = connect.prepareCall("{?=call get_geom_difference()}");
proc.registerOutParameter(1, java.sql.Types.INTEGER);
proc.executeQuery();
ResultSet results = (ResultSet) proc.getObject(1);
出现错误:
org.apache.jasper.JasperException: An exception occurred processing JSP page /commit_changes.jsp at line 25
in line
proc.executeQuery();root cause javax.servlet.ServletException: org.postgresql.util.PSQLException: No results were returned by the query
但是查询
SELECT filedata.num
FROM filedata
Where filedata.num=1;
返回 1
。
错在哪里?
最佳答案
您可以大大简化功能。 (为了问题的缘故,保持简单的功能。)
CREATE OR REPLACE FUNCTION get_geom_difference()
RETURNS integer AS
$BODY$
SELECT num
FROM filedata
WHERE num = 1
LIMIT 1; -- needed if there can be more than one rows with num = 1
$BODY$ LANGUAGE SQL;
不过,从技术上讲,如果数据类型匹配,您在问题中的内容也可以。可以? filedata.num
列是否为 integer
类型?这就是我从示例中收集到的信息。在 your other question由于缺乏信息,我假设 numeric
。至少其中之一会失败。
如果函数的返回类型与返回值不匹配,您会从 PostgreSQL 函数中得到一个错误。如果配置正确,在这种情况下,您的 PostgreSQL 日志将包含详细的错误消息。
当您在 PostgreSQL 中创建上述函数然后调用时,您会看到什么:
SELECT get_geom_difference(1);
来自 psql . (最好在同一个 session 中排除数据库、端口、服务器或用户的混合。)
调用一个接受一个参数并返回一个标量值的简单函数似乎非常简单。 Chapter 6.1 of the PostgreSQL JDBC manual有一个完整的例子,它似乎与你的问题完全一致(不过我的专长是 Postgres 而不是 JDBC)。
关于java - 如何在 Java 中调用 PostgreSQL 过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11859723/