简体   繁体   English

将Node.js MySQL插入多个表

[英]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. 我正在使用AWS Node.js lambda函数,并且尝试插入MySQL数据库中的多个表中。 I am using the mysql node package. 我正在使用mysql节点包。 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. 我有一个JSON对象数组,其中包含标头信息以及对象内部的详细信息数组。 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) 标题表(ID和名称)
  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. 我尝试对Node.js使用标准的“ mysql”库,但是由于connectoin.query(sql,fn)的性质,第二个参数是回调,因此我不确定如何实现此目的。 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 我不确定如何使用标准mysql库在标头和标头内的详细信息进行循环,因为.query函数需要回调而不是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. 您可以使用nodejs utils包中的promisify实用程序将mysql(或模块中的特定功能)包装在Promise中,从而允许您使用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)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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