使用ResultSet.updateRow函数更新可更新视图的行

时间:2015-04-27 14:37:16

标签: java postgresql jdbc resultset updatable-views

我在PostgreSQL服务器上有可更新的视图。

当我从pgAnmin3控制台执行它时,更新查询工作正常,但是当我尝试使用ResultSet.updateRow()方法更新此视图时,我收到以下错误:

  

org.postgresql.util.PSQLException:找不到表的主键

我想我无法为视图指定主键。

我可以在客户端应用程序中为ResultSet.updateRow()方法指定键列吗?或者我可以为WHERE方法指定ResultSet.updateRow()子句吗?

这是我的表格

CREATE TABLE fin.t_year
(
    id serial NOT NULL,
    date_begin date NOT NULL,
    date_end date NOT NULL, 
    year_name character varying(128),
    CONSTRAINT "PK_year" PRIMARY KEY (id)
)

WITH (
  OIDS=FALSE
);


CREATE TABLE fin.t_period
(
    id serial NOT NULL,
    id_year integer NOT NULL,
    per_begin date NOT NULL,
    per_end date NOT NULL, 
    per_name character varying(256),
    CONSTRAINT "PK_period" PRIMARY KEY (id),
    CONSTRAINT "FK_period_year" FOREIGN KEY (id_year)
    REFERENCES fin.t_year (id) MATCH SIMPLE
    ON UPDATE NO ACTION ON DELETE NO ACTION
)

WITH (
  OIDS=FALSE
);


CREATE VIEW fin.vi_period AS 
     SELECT per.id,
        per.per_begin AS "Begin",
        per.per_end AS "End",
        per.per_name AS "Name",
        y.year_name AS "Year"
       FROM fin.t_period per
         JOIN fin.t_year y ON y.id = per.id_year;



CREATE OR REPLACE FUNCTION fin.tgfn_vi_period_update()
RETURNS trigger AS
$BODY$
    DECLARE
        id_row INTEGER;
        id_curr INTEGER;
        result RECORD;
BEGIN
        id_curr = NEW.id;

        -- Replace text identifier with integer primary key
        IF NEW."Year" IS NOT NULL THEN

            SELECT id INTO id_row
                FROM fin.t_year
                WHERE year_name = NEW."Year";
            UPDATE fin.t_period SET id_year = id_row 
                WHERE id = id_curr;

        END IF;


        IF NEW."Begin" IS NOT NULL THEN    

            UPDATE fin.t_period SET per_begin = NEW."Begin"
                WHERE id = id_curr;
        END IF;
        IF NEW."End" IS NOT NULL THEN    

            UPDATE fin.t_period SET per_end = NEW."End"
                WHERE id = id_curr;
        END IF;
        IF NEW."Name" IS NOT NULL THEN
            UPDATE fin.t_period SET per_name = NEW."Name"
                WHERE id = id_curr;
        END IF;



        SELECT * INTO result FROM fin.vi_period WHERE id = id_curr;
        RETURN  result;

END;
$BODY$
LANGUAGE plpgsql VOLATILE
  COST 100;

此插入语句正常

UPDATE fin.vi_period SET "Year" = 'new_year_name' WHERE id  = 10;

但是这个java代码的问题

statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = statement.ExecuteQuery("SELECT * FROM fin.vi_period;");


rs.absolute(pos + 1);
rs.updateString("new_year_name");
rs.updateRow();

1 个答案:

答案 0 :(得分:1)

问题是您正在查询视图,并且该视图没有主键(我不确定PostgreSQL是否可以实现,但大多数数据库都不支持)。 JDBC驱动程序需要主键才能使结果集可更新。

换句话说:您无法通过结果集更新此视图。您需要使用显式UPDATE语句,或者直接在基础表上执行此操作,而不是通过视图。