【问题标题】:Insert into two dependent tables in MySQL with node.js使用 node.js 插入 MySQL 中的两个依赖表
【发布时间】:2016-05-02 15:04:09
【问题描述】:

我是 MySQL 和 node.js(以及回调)的新手。我尝试将数据插入到表B中,这取决于表A中的数据。这是一个示例。

员工表(表A):

CREATE TABLE employees (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(50),
  location varchar(50),
  PRIMARY KEY (id)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

年龄表(B表,我故意不在A表中加入年龄列):

CREATE TABLE age (
  id int(11) NOT NULL AUTO_INCREMENT,
  index_id int(11),
  age int(50),
  PRIMARY KEY (id)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

问题

对于插入到表 A 中的每一行,我可以获得它的 id。我想用id作为B表中的index_id,将对应的年龄信息插入到年龄表B中。当我插入多行时出现问题。

示例

我实现了以下功能来实现上述目标。

var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "sitepoint"
});

function insert_employees() {
    var employees = [
        {name: 'Jasmine', location: 'Australia', age: 24},
        {name: 'Jay', location: 'India', age: 25},
        {name: 'Jim', location: 'Germany', age: 26},
        {name: 'Lesley', location: 'Scotland', age: 27}
    ];
    var name_id;
    for (var i = 0; i < 4; i++) {
        var employee = employees[i];
        var command = sprintf('INSERT INTO employees (name, location) VALUES ("%s", "%s");', employee.name, employee.location);
        con.query(command, function (err, res) {
            if (err) throw err;
            name_id = res.insertId;
            console.log('Last insert ID in employees:', res.insertID);

            // insert age here
            var age = employee.age;
            var command = sprintf('INSERT INTO age (index_id, age) VALUES (%d, %d);', name_id, age);
            con.query(command, function (err, res) {
                if (err) throw err;
            });
        });
    }
}

输出

员工表没问题,但是对于年龄表,所有字段的年龄列都是27,而不是24、25、26、27

问题

我认为问题在于我滥用回调功能,但我仍然不知道如何解决它。有人可以帮我吗?非常感谢!

【问题讨论】:

  • var age = employee.age 之后放一个; 尽管JS 支持
  • 谢谢,已添加。
  • 你能提供你的表格 DDL
  • 数据定义语言?我使用我在开始时编写的 MySQL 脚本来创建我的表。 :)
  • 还是一样,:(...

标签: mysql node.js database


【解决方案1】:
var employee = employees[i];

将上面的行更改为下面的行,使变量employee具有正确的范围:

let employee = employees[i]; 

将以下内容添加到脚本的开头,以便运行:

'use strict';

【讨论】:

    猜你喜欢
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    相关资源
    最近更新 更多