2
我正在使用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)
謝謝JB Nizet先生......我剛學習JDBC連接。 – 2013-04-04 16:51:55