简体   繁体   中英

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. I have another table for storing subject details which also contains Student_id which has foreign key relations with previously mentioned column.

How can I use the same id value for both table. Now I am using java PreparedStatement to send query separately for updating both tables (without ids). 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? Can some one help with java implementation.

Db schema is as follows: 在此处输入图片说明

Since there is no table name mentioned, I'm considering the table name being used as ParamsTable and here is the flow!

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

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!

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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