简体   繁体   中英

mysql insert rows in multiple tables

I have a database with multiple tables, in al the tables there have to be a row because else my query is going wrong. In one of my insert pages i insert al the rows seperatly in the tables. Is there a more efficient and safe way to do this? Maybe in Mysql (CASCADE)?

afaik there is no other way to same data into different tables in same statement. But you can try using transactions.

START TRANSACTION;
insert into t1 (field1, field2) values ('data1','data2');

After inserting the data you can check them if they are ok and if everything is like expected than commit your queries:

COMMIT;

or do a rollback, which removes the changes sience "START TRANSACTION".

ROLLBACK;

I suggest using a MySQL Transaction, which allows you to rollback the inserts if one of them fails. SQL to start the transaction:

START TRANSACTION;

At this point, do your inserts, if one of them errors then rollback:

ROLLBACK;

If all of the inserts complete with no errors, you can commit your inserts:

COMMIT;

MySQL docs for transactions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM