node.js mysql insert id -我如何在插入查询之外暴露插入id
node.js mysql insert id - how do I expose the insert id outside of the insert query?
假设我有一个json格式(或任何格式)的值列表,我需要插入到mysql表中。插入之后,我需要结果。insertId暴露在mysql的外部。查询电话。有办法做到吗?(请不要问我为什么需要这个:我知道如何解决这个问题。我只是想知道这种情况是否可能)。理想情况下,每个数组项的描述和插入Id应该打印到屏幕上。相反,我得到一个空数组。是的,我知道将console.log 放入回调的将实现这一点。这不是我需要的答案。是否有可能在回调之外公开插入Id ?
var todos = require('./todos.json');
var mysql = require('mysql');
var mysql_pool = mysql.createPool({
host : 'localhost',
user : 'myuser',
password : 'mypwd',
database : 'mydb'});
var todoArray = [];
todos.forEach(function(todo) {
mysql_pool.query("INSERT INTO todos(description) VALUES(?)", todo.description, function(err, result){
if (err) {
console.log(" Unable to insert: " + err);
throw err;
}
todoArray.push({description: todo.description, desc_id: result.insertId});
});
});
console.log(todoArray);
我同意Brian关于查询回调函数在console.log命令之后完成的异步性质,因此没有结果。关于查询循环,下面的方法通过使其顺序来解决这个问题。下一个数据将在运行前一个查询回调时加载。
问题是你不知道什么时候用你当前的方法处理整个数组。如果您知道最后一个循环,则可以将该数组作为查询回调的最后一步来处理。在此之前,只需加载数组。
使用迭代器next命令将给出下一个值,如果是最后一个循环则给出一个指示符。
希望是这样的:
//use require to get node to parse in the json file as an object
//set todo as iterator type
var todos = require("./path/todos.json")[Symbol.iterator](),
todoArray = [],
todo = todos.next()
//todos.next() iterator cammand returns {done: true/false, value: { }}
//we want to know the end so we can process todoAray
do {
mysql_pool.query("INSERT INTO todos(description) VALUES(?)",
todo.value.description,
function(err, result){
if (err) { console.log(" Unable to insert: " + err); throw err; }
todoArray.push({description: todo.value.description, desc_id: result.insertId})
todo = todos.next()
If(todo.done === true){
console.log(todoArray)
}
});
}while (!todo.done)
相关文章:
- 在iframe代码中动态插入子id
- 包含插入的Meteor方法没有返回记录ID作为结果
- 如何将文本插入到几个带有 id 的文本区域中的一个文本区域中
- node-mssql 事务插入 - 返回插入的 id
- 我想单击一个
- 并获取 id 以通过 POST 将其插入数据库,可以吗?
- AJAX添加多个事件插入前重置Id
- 如何获取插入到表中的行的自动生成的ID
- JQuery 数据表添加新行,如果该行已经存在,请将其删除并为该 ID 插入新行
- 环回 - 基于 id 以外的其他属性的 REST 更新插入/更新
- 如何在SQLite中获取上次插入的行ID
- 我正在尝试遍历 id 数组,如果不存在 id,则插入一个 mongodb 文档.我怎样才能让他们坚持下去
- 当 Javascript 中的 POST ID 元素插入 PDO 时,数据库中没有结果
- 插入行 javascript 时递增 id
- 仍然没有添加到 DOM 中,但如果插入了警报/确认,则会获取标签 ID
- 将单击元素的类和父元素的 ID 插入到另一个图像中
- 将字段与 id 匹配并插入数据 - 流星
- 在 jQuery 中插入一个 CSS id
- 使用 Ajax 和 jQuery 将单选按钮值中的 ID 插入数据库
- jQuery/Javascript:在jSON对象中插入ID
- node.js mysql insert id -我如何在插入查询之外暴露插入id