我是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。我想在表B中使用id作为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
问题:
我认为问题在于我滥用回调功能,但我仍然不知道如何解决它。任何人都可以帮我吗?非常感谢!
答案 0 :(得分:2)
var employee = employees[i];
将上述行更改为以下,以便变量员工具有正确的范围:
let employee = employees[i];
将以下内容添加到脚本的开头,以便让它起作用:
'use strict';