简体   繁体   English

Java DB如何将外键的值插入表列

[英]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.

相关问题 如何在Java中使用外键从表中检索值? - How to retrieve values from from a table with Foreign Keys in Java? Java/Mysql 从一个表中选择主键值并将它们作为外键插入到另一个表中 - Java/Mysql Selecting Primary Key values from one table and Insert them to another table as Foreign Keys 如何将数据插入带有外键的表中? - How do I insert data into a table with foreign keys? 如何使用MySql在Java中编写查询以使用外键插入数据 - How to write query in java to insert data with foreign keys using MySql 插入数据库表Java - insert into DB table java 在Java中将值插入TABLE - INSERT values to TABLE in java 如何使用mybatis在数据库中插入java HashMap键和值作为列 - How to insert java HashMap keys and values as columns in database using mybatis 如何使用Java和MySQL将值插入到已可用表的特定列中 - How to insert values from into specific column in already available table using Java and MySQL 如何使用rest api插入hibernate中的表,并且该表2列是另一个表的外键? - How to insert into a table in hibernate using rest api and on that table 2 column are foreign key of another table? 使用java在mysql中插入带有外键的表 - Insert into a table with a foreign key in mysql using java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM