【发布时间】:2016-03-13 18:40:58
【问题描述】:
我刚开始学习 Java JDBC,我尝试创建一个示例项目。我创建了两个 Prepared Statements,我在其中为我的表插入两个查询。主键的第一个表和外键的第二个表。使用 Statement_RETURN.GENERATED_KEYS 正在返回主键的 Id,但在我的外键中它没有填充并给我一个 null 值。
父表
子表
查询:
String insertALLSECTION_LIST = "INSERT INTO ALLSECTIONS_LIST (SECTION_NAME)"
+ "VALUES (?)";
String insertALLSECTIONS_SETTINGS = "INSERT INTO ALLSECTIONS_SETTINGS (SECTION_POPULIMIT,ROOM_ASSGN,ADVISER_ASSIGNED,SESSION_ASSIGNED,YRLEVEL_ASSGN,SCHOOL_YEAR)"
+ "VALUES(?,?,?,?,?,?)";
准备好的陈述
ResultSet generatedKeys = null;
try (Connection myConn = DBUtil.connect())//Connection
{
myConn.setAutoCommit(false);//Turn off auto commit
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST,Statement.RETURN_GENERATED_KEYS))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
generatedKeys = myPs.getGeneratedKeys();
if (generatedKeys.next())//Return ID
{
sectionID = generatedKeys.getInt(1);
}
else
{
throw new SQLException("No generated section ID returned");
}
}//end of try
finally
{
if (generatedKeys != null) generatedKeys.close();
}//end of finally
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTIONS_SETTINGS))//Prepared Statement
{
myPs.setInt(1,inputStudentLimit);
myPs.setString(2, inputRoomAssign);
myPs.setString(3, inputAdviserAssign);
myPs.setString(4, inputSession);
myPs.setString(5, inputYearLevel);
myPs.setString(6, inputSchoolYear);
myPs.executeUpdate();
myConn.commit();
JOptionPane.showMessageDialog(null, "Insert Successful");
}//end of try
}//end of try
第一个表(ALLSECTIONS_LIST)
正如您在此处看到的,主键正在填充。
在这里我的 SECTION_ID 列给了我空值。
但是当我为我的表运行查询时。仍然给我的外键一个 Null 值。随意发表评论。谢谢。
【问题讨论】:
-
返回生成的键的我的语句正在返回主键的 Id,但它没有填充到外键中。 我在这里有点困惑。我没有看到您将密钥(即您从第一个 PS 获得的
sectionID)插入到任何地方的第二个 PS 中。我错过了什么吗? -
嗨! @user2004685 我刚刚更新了我的帖子。请再次检查。谢谢!