[英]Java DB How to Insert Values for Foreign Keys into Table Column
I am using java DB database and NetBeans 8.0 for a desktop application 我正在将Java DB数据库和NetBeans 8.0用于桌面应用程序
I am also using a PreparedStatement to query the database. 我还使用PreparedStatement来查询数据库。
below is the code for creating the tables. 以下是用于创建表的代码。
CREATE TABLE ALUMNUS (
ALUMNUA_ID INT NOT NULL PRIMARY KEY
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
FIRST_NAME VARCHAR (45),
LAST_NAME VARCHAR (45),
OTHER_NAME VARCHAR (100)
);
CREATE TABLE DUES (
ID INT NOT NULL PRIMARY KEY
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
PAYMENT_YEAR DATE,
AMOUNT DOUBLE,
ALUMNUS_ID INT
);
--FOREIGN KEY
ALTER TABLE APP.DUES
ADD FOREIGN KEY (ALUMNUS_ID) REFERENCES APP.ALUMNUS(ID);
Now I want to insert, delete and update the foreign key values in APP.DUES table. 现在,我要插入,删除和更新APP.DUES表中的外键值。 what is the best option; 最佳选择是什么? trigger , stored procedure or the preparedstatement? 触发器,存储过程还是preparestatement?
An example will be good. 一个例子会很好。
If you want to primarily insert into the DUES table, you would use a sub select in SQL. 如果要主要插入DUES表,则可以在SQL中使用子选择。 I havent tested it with Java DB, but it basically looks like: 我还没有使用Java DB对其进行测试,但是它基本上看起来像:
INSERT INTO DUES(PAYMENT_YEAR, AMOUNT,ALUMNUS_ID)
VALUES(2014, 100.0,
(SELECT ALUMNUA_ID from ALUMNUS where ...));
You need to catch the "not found" error case and prepend a INSERT (and need to catch the duplicate case for that as well). 您需要捕获“未找到”错误的大小写并在INSERT之前加上(并且也需要捕获重复的大小写)。
See also: Insert Data Into Tables Linked by Foreign Key 另请参阅:将数据插入到由外键链接的表中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.