Question

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);
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top