java如何根据主键的值更改外键?
我现在有两张桌子,table talkview:
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| titlename | varchar(64) | NO | | NULL | |
| postname | varchar(64) | NO | | NULL | |
| counts | varchar(11) | YES | | 0 | |
+-----------+-------------+------+-----+---------+----------------+
和table maintalk:
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(64) | NO | | NULL | |
| text | varchar(64) | NO | | NULL | |
| username | varchar(64) | NO | | NULL | |
| talk_id | int(10) | YES | MUL | NULL | |
+----------+-------------+------+-----+---------+----------------+
现在我想将数据一起插入这些表中,“talk_id”将根据table talkview中的“id”自动更改
在Java中,我尝试了这段代码,但“talk_id”没有变化:
public void posttalk(String title, String con, String name){
connection = DBConection.getConnection();
Statement stmt = null;
String SQL_1 = "insert into talkview(titlename,postname) values(? , ?)";
String SQL_2 = "insert into maintalk(title,text,username) values(? , ? , ?)";
try {
connection.setAutoCommit(false);
PreparedStatement preparedStatement = connection.prepareStatement(SQL_1);
preparedStatement.setString(1, title);
preparedStatement.setString(2, name);
Integer a = preparedStatement.executeUpdate();
preparedStatement = connection.prepareStatement(SQL_2);
preparedStatement.setString(1, title);
preparedStatement.setString(2, name);
preparedStatement.setString(3, con);
Integer b = preparedStatement.executeUpdate();
connection.commit();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
try {
connection.rollback();
stmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
sqle.printStackTrace();
} finally {
DBConection.closeConnection(connection);
}
}
# 1 楼答案
在第一个名为
talkview
的表中插入一些数据之后。您可以使用最大主键检索插入的最后一条记录,因为PK是自动递增的,然后将其放在maintalk
表的talk_id
列上。您可以执行以下代码来检索它