我正在使用JDBC和MySql。我将数据插入一个表并获取其主键transactionid
。现在将带有transactionid的数据插入到另一个表中。
我的代码:
if (connection != null) {
System.out.println("Now connection is created successfully");
stmt=connection.createStatement();
Date date=new Date();
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String time=formatter.format(date);
System.out.println("time is "+time);
//insert transaction id and minimum support....
mySql = "insert into Transaction (minimumsupport)
values('"+minimumSupport+"')";
stmt.executeUpdate(mySql,Statement.RETURN_GENERATED_KEYS);
ResultSet rt=stmt.getGeneratedKeys();
int transactionId;
while(rt.next()){
transactionId=rt.getInt(1);
System.out.println("the transaction id is: "+transactionId);
}
rt.close();
int i;
Statement stmt1;
for(i=0;i<productArray.length;i++)
{
stmt=connection.createStatement();
System.out.println("first value: "+productArray[i]);
mySql = "insert into
Producttransaction(transactionid,productId)
values('"+transactionId+"','"+productArray[i]+"')";
stmt.executeUpdate(mySql);
status="productAdded";
System.out.println("product added");
}
//To insert the data into the tables....
connection.close();
引发以下异常:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row: a foreign key constraint fails (`aprioridb`.`Producttransaction`, CONSTRAINT `fk_Productid` FOREIGN KEY (`transactionid`) REFERENCES `Product` (`productId`) ON DELETE NO ACTION ON UPDATE NO ACTION)
答案 0 :(得分:0)
您的外键约束似乎是错误的:
FOREIGN KEY (transactionid) REFERENCES Product (productId)
应该是
FOREIGN KEY (productid) REFERENCES Product (productId)
此外,了解准备好的语句以避免SQL注入攻击,拥有更强大,更高效的代码。