문제

I need to add a foreign key in the tables after creation their.

I use this request: ALTER TABLE lessons ADD FOREIGN KEY (id_teacher) REFERENCES teachers (id);

After it executed, I get error: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: PUBLIC.LESSONS

How can I fix it?

Sending a query: Statement statement = connection.createStatement(); statement.execute(request);

The entire query:

CREATE TABLE lessons (
id int IDENTITY, 
lesson_name varchar(50) NOT NULL, 
id_teacher int NOT NULL,
id_group int NOT NULL
);

CREATE TABLE teachers (
id int IDENTITY,
teacher_name varchar(50) NOT NULL,
id_lesson int NOT NULL,
id_group int NOT NULL
);


CREATE TABLE groups (
id int IDENTITY,
group_name varchar(50) NOT NULL,
id_lesson int NOT NULL,
id_curator int NOT NULL
);

ALTER TABLE lessons 
ADD FOREIGN KEY (id_teacher) REFERENCES teachers (id) 
ADD FOREIGN KEY (id_group) REFERENCES groups (id);

ALTER TABLE teachers 
ADD FOREIGN KEY (id_lesson) REFERENCES lessons (id) 
ADD FOREIGN KEY (id_group) REFERENCES groups (id);

ALTER TABLE groups 
ADD FOREIGN KEY (id_lesson) REFERENCES lessons (id) 
ADD FOREIGN KEY (id_curator) REFERENCES teachers (id);
도움이 되었습니까?

해결책

The error is returned because you are sending the whole script together as one statement. It is compiled before it is executed. When the ALTER TABLE statement is compiled, the table has not been created yet.

Execute each statement separately. Also as commented before, you need one ALTER TABLE statement per foreign key.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top