MySQL database problem, how to add two tables (a table, B table) in the same operation, and add the ID of B table to the A table field, B table ID automatically grow
create a stored procedure in the database, such as the name of the stored procedure called Test
in Java and normal use of SQL, sql = "Call Test (B1,B2)", B1 and B2 assume that you are going to insert data from table B
Suppose the structure of Table B is (ID int auto_incremet, B1 int, B2 int)
Suppose the structure of a table is (ID int)
CREATE Test (B1 int, B2 int) #假设A1和A2是将要插入b表中的数据
BEGIN
declare new_id as int; #声明自增长所添加的ID
INSERT into B (B1,B2) values (B1,B2); #给b插入新的记录
Select last_insert_id () into new_id; #取得新插入记录的ID
INSERT into a (ID) values (new_id); #把新插入的ID写入a表
Select new_id; #如果需要的话存储过程返回新得到的ID给客户端
END
Note: It is recommended to use a stored procedure instead of using select LAST_INSERT_ID () directly in a Java program, since this function is to return the last inserted self-growing ID when the current port is opened, and if the stored procedure is not used, It may be that the current link is closed, or another application has inserted a new record in another table with a self-growing ID, and the ID you retrieved is wrong.
MySQL Database---Insert data above two tables at the same time