Reputation: 3002
So after creating tables using jdbc, I have this code to make one to many relationship between UserInfoTable and ContactTable and UserInfoID as foreign key.
String addConstraint = "alter table ContactTable"+
"ADD CONSTRAINT FK_ContactTable_UserInfoTable"+
"FOREIGN KEY(UserInfoID)"+
"REFERENCES UserInfoTable (UserInfoID)"+
"ON UPDATE CASCADE"+
"ON DELETE CASCADE";
But when I execute this,
con.prepareStatement(addConstraint).executeUpdate();
I'm getting
java.sql.SQLException: Incorrect syntax near the keyword 'CONSTRAINT'.
I'm really confused. I handcoded this query several times in sql server and I think my syntax is correct because it always executed successfully, why not when executed by java code?
Upvotes: 0
Views: 1138
Reputation: 1374
You are concatenating strings but the different segments have no spaces, this could be causing keywords to be bunched together with your data creating invalid keywords.
It is simple but this may be all you need:
String addConstraint = "alter table ContactTable "+
"ADD CONSTRAINT FK_ContactTable_UserInfoTable "+
"FOREIGN KEY(UserInfoID) "+
"REFERENCES UserInfoTable (UserInfoID) "+
"ON UPDATE CASCADE "+
"ON DELETE CASCADE";
Upvotes: 3