我正在将 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)