解析CSV文件..管理主键的问题?

时间:2011-02-14 09:08:00

标签: database oracle loops stringtokenizer

我刚刚创建了一个java文件来解析csv文件并将它们保存到oracle数据库中..但是我需要一个字段ID作为主键...而且我有点困惑abt循环..

1 个答案:

答案 0 :(得分:1)

我认为您需要做的就是利用一个序列(如Ronnis所建议的)

就是这样

CREATE SEQUENCE FIELD_ID_SEQ START WITH 1 INCREMENT BY 1 NOCYCLE NOCACHE; 
/*NOTE THE SEQUENCE, WHILE INCREMENTING, IS NOT GUARANTEED TO BE 1,2,3,4...N ->expect gaps in the #*/

现在要么在您保存数据的Java应用程序中:

"INSERT INTO TABLE_OF_CSV(FIELD_ID, FIELD_COLA, FIELD_COLB) VALUES(FIELD_ID_SEQ.NEXTVAL, ?,?);"

OR


现在,如果你正在使用一个程序(或程序包中的程序),你可以这样做(注意这会将主键返回给调用应用程序)

create procedure insertIntoCSVTable(pCOLA IN TABLE_OF_CSV.FIELD_COLA%TYPE 
                                  , pCOLB IN TABLE_OF_CSV.FIELD_COLB%TYPE
                                  , pFIELD_ID OUT TABLE_OF_CSV.FIELD_ID%TYPE)
AS
BEGIN

    INSERT INTO TABLE_OF_CSV(FIELD_ID, FIELD_COLA, FIELD_COLB) 
    VALUES(FIELD_ID_SEQ.NEXTVAL, pCOLA, pCOLB)
    RETURNING FIELD_ID
    INTO pFIELD_ID
    ;

END insertIntoCSVTable;

假设您已经在java代码中循环(假设逐行插入),则不需要循环


OR


您可以使用触发器在表格中插入新值: 创建或替换

TRIGGER TABLE_OF_CSV_TRG BEFORE INSERT ON TABLE_OF_CSV 
FOR EACH ROW 
BEGIN
  <<COLUMN_SEQUENCES>>
  BEGIN
    IF :NEW.FIELD_ID IS NULL THEN
      SELECT FIELD_ID_SEQ.NEXTVAL INTO :NEW.FIELD_ID FROM DUAL;
    END IF;
  END COLUMN_SEQUENCES;
END;