0
String ag ="ALTER TABLE QUESTION"+
            "(ADD  FOREIGN KEY (a_status) REFERENCES ANSWER(a_status))";

                      stmt.executeUpdate(ag);

Error message: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY (a_status) REFERENCES ANSWER(a_status))' at line 1

ughai
  • 9,830
  • 3
  • 29
  • 47
Mv4491
  • 1
  • 1
    possible duplicate of [Add Foreign Key to existing table](http://stackoverflow.com/questions/10028214/add-foreign-key-to-existing-table) – ughai May 28 '15 at 06:33

3 Answers3

0

This should be correct. See the offical documentation:

String ag ="ALTER TABLE QUESTION ADD FOREIGN KEY (a_status) REFERENCES ANSWER(a_status)";
Jens
  • 67,715
  • 15
  • 98
  • 113
0
String ag ="ALTER TABLE QUESTION ADD CONSTRAINT (question_answer_ibfk1) FOREIGN KEY (a_status) REFERENCES ANSWER(a_status)";

In general

ALTER TABLE Child_tblName
ADD CONSTRAINT 'give any name to the foreign key generally I do Child_tblName_Parent_tblName_ibfk_number' FOREIGN KEY ('Child_tblName's Column') REFERENCES Parent_tblName('Parent_tblName's Column')
Vishal
  • 211
  • 2
  • 8
  • thank you sir **@Ole Albers!** for adding the good CodeBlock view for better readability , I am new to stackoverflow so learning these edition things. – Vishal May 28 '15 at 07:16
0
String ag ="ALTER TABLE QUESTION ADD CONSTRAINT (question_answer_fk1) FOREIGN KEY (a_status) REFERENCES ANSWER(a_status)";

Also you can have more condition specific to add:

  • ON DELETE SET NULL/CASCADE
  • ON UPDATE SET NULL
Sagar Panda
  • 561
  • 3
  • 17