MySQL Database---Insert data above two tables at the same time

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.