简体   繁体   中英

Node.js mysql insert into multiple tables

I am using an AWS Node.js lambda function and I am attempting to insert into multiple tables in my MySQL database. I am using the mysql node package. I have two tables (header and detail) in the database. I have an array of JSON objects that includes the header info with an array of the detail info inside the object. It looks like this:

{
  id:1,
  name: "bob",
  detail: [salary: 50000, age: 35]
}, {
  id:1,
  name: "jane",
  detail: [salary: 60000, age: 28]
}

I need to loop through each object in this array and populate:

  1. header table (id and name)
  2. detail table for that header (salary, age)

I tried using the standard "mysql" library for Node.js, but due to the nature of the connectoin.query(sql, fn), the second parameter is a callback, and I'm not sure how I would pull this off. I'm not sure how I could loop through the headers and details within the headers using the standard mysql library since the .query function requires a callback and not a Promise

Thanks

You could use the promisify utility from the nodejs utils package to wrap the mysql (or specific functions in the module) in a Promise, allowing you to use async/await. Something like this:

    const mysql = require('mysql')
    const util = require('util')
    const pool = mysql.createPool({ ... })
    ...
    pool.query = util.promisify(pool.query)
    ...
    try {
    var result = await pool.query('SELECT * FROM users')
    } catch(err) {
        throw new Error(err)
    }

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