简体   繁体   English

将相同的auto_increment id插入两个不同的表中

[英]Inserting same auto_increment id into two different tables

I am using two tables in a database. 我在数据库中使用两个表。 First table is to store personal details of students where one column is auto_increment named as Student_id. 第一个表用于存储学生的个人详细信息,其中一列名为auto_increment的名称为Student_id。 I have another table for storing subject details which also contains Student_id which has foreign key relations with previously mentioned column. 我还有另一个用于存储主题详细信息的表,其中还包含Student_id,该ID与前面提到的列具有外键关系。

How can I use the same id value for both table. 如何为两个表使用相同的ID值。 Now I am using java PreparedStatement to send query separately for updating both tables (without ids). 现在,我使用java PreparedStatement单独发送查询以更新两个表(不带ID)。 like, 喜欢,

PreparedStatement preparedStatement = connection.prepareStatement("query");
preparedStatement.setString(i,"parameter");
preparedStatement.executeUpdate();

I have done the same thing for two tables, but is it possible to update with the same auto_id in both table? 我对两个表做了同样的事情,但是是否可以在两个表中使用相同的auto_id更新? Can some one help with java implementation. 可以帮助实现Java。

Db schema is as follows: db模式如下: 在此处输入图片说明

Since there is no table name mentioned, I'm considering the table name being used as ParamsTable and here is the flow! 由于未提及表名,因此我正在考虑将该表名用作ParamsTable ,这就是流程!

You do an insert as mentioned in your code (posted in the question)! 您按照代码中的说明进行插入(在问题中发布)!

PreparedStatement preparedStatement = connection.prepareStatement("query");
preparedStatement.setString(i,"parameter");
preparedStatement.executeUpdate();

After this, you will have to fire a SELECT query to get the last inserted id (the auto-incremented id) from your ParamsTable 之后,您将必须执行SELECT查询,才能从ParamsTable获取最后插入的ID(自动递增的ID)

ResultSet resultSet = preparedStatement.executeQuery("SELECT last_insert_id() AS last_inserted_id");
String lastInsertedID = resultSet.getString("last_inserted_id");

You will now be holding the last inserted id of the auto_increment column, which you could use further in any table of your choice! 现在,您将保留auto_increment列的最后一个插入的ID,您可以在选择的任何表中进一步使用它!

Hope this helps! 希望这可以帮助!

try this: 尝试这个:

PreparedStatement preparedStatement = connection.prepareStatement("query");
preparedStatement.setString(i,"parameter");
preparedStatement.executeUpdate();
ResultSet generatedKeys = preparedStatement.getGeneratedKeys()
if (generatedKeys.next()) {
    user.setId(generatedKeys.getLong(1));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM