开发者

How to get an automatically incremented column value when inserting a row into a table in mysql using java?

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 开发者_Python百科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);


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜