如何使用java在mysql的表中插入一行时获得自动递增的列值?
如何插入到 table1 中,例如: INSERT INTO table1 (description) VALUES ('Some test description here');
并让它返回自动递增的 ID,以便我可以在 table2 中插入一行?不保证描述是唯一的。我正在使用 Java PreparedStatement
来插入当前使用 execute()
的值,
我有以下表结构:
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
插入成功完成后立即运行此查询:
SELECT LAST_INSERT_ID()
run this query right after the insert completes succesfully:
SELECT LAST_INSERT_ID()
试试这个:
观察数据和数据的值ID。
你不需要触发 insert &分别选择查询。
Try this:
Observe values of data & id.
You don't need to fire insert & select queries separately.