Recently, when I wrote the backend interface of the student Declaration project, I found that I needed to get the database auto-generated primary key, because I wanted to insert project information into Project table, get the project ID generated, and then insert the Project ID and instructor ID into the Project_member table.
At first, after inserting the project, using select LAST_INSERT_ID () to get the generated ID, it was later found that the returned result after the insert operation was completed with an automatically generated ID. Available Rows.insertid Access
Code:
Use transactions to insert project and Project_member tables Conn.begintransaction (function (err) {if (err) {SendData (Req,res,next,conn,err) ; }else{//Insert Project Information conn.query (' INSERT INTO Project ' in Project table (Project_category_id,project_status,project_creator_id,pro Ject_name,project_start, ' + ' project_end,project_source,project_aid,project_background,project_describe,project_ Innovation, ' + ' project_plan,project_prospect,project_budget,project_resourcerequired) ' + ' VALUES (' +categor Y+ ', 0, ' +userid+ ', "' +name+ '", "' +starttime+ '", "' +endtime+ '", 1, "' +aid+ '", ' + ' "' +background+ '", "' +describe+ '", "' + Innovation+ ' "," ' +plan+ ' "," ' +prospect+ ' "," ' +budget+ ' "," ' +resourcerequired+ ' ") ', function (err,rows) {if (err) { Conn.rollback (function () {//If the rollback senddata (req,res,next,conn,err) fails; }); } var Insertid = rows.insertid;//Gets the auto-generated ID console.log (INSERTID); Insert the project and Instructor's correspondence in the member table Conn.queRy (' INSERT into Project_member (project_id,user_id,project_member_role,project_member_task) ' + ' VALUES (' +inse Rtid+ ', ' +teacherid+ ', 2, "instructor") ', function (err,rows) {if (err) {Conn.rollback (function () {/ /if failed rollback senddata (REQ,RES,NEXT,CONN,ERR); }); } conn.commit (function (ERR) {//COMMIT TRANSACTION if (err) {Conn.rollback (func tion () {senddata (req,res,next,conn,err); }); } console.log (' success! '); var data = {status:true, message: "Declared success"}conn.release ( ); Res.send ({"Data":d ATA}); }); }) }) })
Nodejs+mysql get auto-generated ID when inserting a record