[英]Insert into two dependent tables in MySQL with node.js
我是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
问题 :
我认为问题在于我滥用回调功能,但我仍然不知道如何解决它。 任何人都可以帮我吗? 非常感谢!
var employee = employees[i];
将上面的行更改为以下,以便变量employee具有正确的范围:
let employee = employees[i];
将以下内容添加到脚本的开头,以便让它工作:
'use strict';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.