Creating a foreign key in Java db (Netbeans)

[亡魂溺海] 提交于 2019-12-14 01:42:32

问题


I've been having problems creating a foreign key in Java Db through Netbeans. I'm pretty sure I have to use an SQL command to change an attribute in the PLAYERS table into a foreign key as I can only specify primary keys through the interface. I have tried executing this command:

ALTER TABLE PLAYERS ADD CONSTRAINT TEAMNUM_FK
Foreign Key (TEAMNUM) REFERENCES TEAM (TEAMNUM);

It's supposed to add/alter TEAMNUM in the PLAYERS table to a foreign key related to a primary key in TEAM table so that the TEAMNUM is consistant in both tables but it gives error:

Error code -1, SQL state X0Y44: Constraint 'TEAMNUM_FK' is invalid: there is no unique or primary key constraint on table '"APP"."TEAM"' that matches the number and types of the columns in the foreign key. Line 1, column 1

If anyone could help that would be great. thanks.


回答1:


The error message is pretty clear:

there is either no primary key defined for the table TEAM, or the PK consists of different columns than just (teamnum) or the datatype of the teamnum column in PLAYERS doesn't match the data type of the column teamnum in the table team.

As you have shown your table definitions, I cannot tell which of three alternatives that the error messages explains is relevant in your case.




回答2:


This is the correct way to do it, after creating the table in the netbeans IDE, select table TEAM and right click Foreign Keys and select execute Command and paste the code below

Alter Table APP.PLAYERS
Add FOREIGN KEY (TEAMNUM_FK)
References APP.TEAM (TEAMNUM);   

Next select table Team again and select refresh

ps: Let's assume APP is your default schema



来源:https://stackoverflow.com/questions/8918904/creating-a-foreign-key-in-java-db-netbeans

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!