1

How can I insert into table1 like: INSERT INTO table1 (description) VALUES ('Some test description here'); and have it return the automatically incremented ID so that I can then insert a row into table2? The description is not guaranteed to be unique. I am using a Java PreparedStatement to insert the value currently with execute()

I have the following table structure:

CREATE TABLE table1 ( table1ID INTEGER NOT NULL AUTO_INCREMENT, description VARCHAR(255) NOT NULL, CONSTRAINT PK_table1 PRIMARY KEY (table1ID) ); CREATE TABLE table2 ( table1ID INTEGER NOT NULL, personID INTEGER NOT NULL, CONSTRAINT PK_table2 PRIMARY KEY (table1ID, personID) ); ALTER TABLE table2 ADD CONSTRAINT FK_table1_table2 FOREIGN KEY (table1ID) REFERENCES table1 (table1ID); ALTER TABLE table2 ADD CONSTRAINT FK_table2_person FOREIGN KEY (personID) REFERENCES person (personID); 
1

2 Answers 2

3

run this query right after the insert completes succesfully: SELECT LAST_INSERT_ID()

Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

PreparedStatement st = con.prepareStatement( "Insert into table1 (name) values ('test desc')", Statement.RETURN_GENERATED_KEYS); st.executeUpdate(); ResultSet rs = st.getGeneratedKeys(); if(rs.next()) { int data = rs.getRow(); int id = rs.getInt(1); } 

Observe values of data & id.

You don't need to fire insert & select queries separately.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.