Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALTER TABLE FOREIGN KEY from java to mysql

Well, I want to make a modification in my database, so I need to use alter table but java seems to have problems making that.

This is the sentence

ALTER TABLE loans ADD FOREIGN KEY (id_reader) REFERENCES readers (id);

how do you execute it?

I was doing this:

rawStatement="ALTER TABLE loans ADD FOREIGN KEY (id_reader) REFERENCES readers (id);";
currentStatement = conn.createStatement();
currentStatement.execute(rawStatement); 

is the last line correct?

As far I know, execute must run everything.

like image 379
Lostuser23 Avatar asked Aug 25 '26 13:08

Lostuser23


2 Answers

Use this:

executeUpdate() 

instead of

execute()

Also if the constraint is already present it will throw an exception

Other things you should look out for:

  • Does the user have the privileges to alter the table?
like image 60
Aditya Naidu Avatar answered Aug 27 '26 03:08

Aditya Naidu


Try with the below code:

rawStatement="ALTER TABLE loans ADD FOREIGN KEY (id_reader) REFERENCES readers (id)"; 
PreparedStatement ps = conn.prepareStatement(rawStatement);
ps.executeUpdate();
like image 20
Tilaka Technologies Avatar answered Aug 27 '26 05:08

Tilaka Technologies