繁体   English   中英

node.js mysql插入ID-如何在插入查询之外公开插入ID?

[英]node.js mysql insert id - how do I expose the insert id outside of the insert query?

假设我有一个需要插入到mysql表中的json格式(或任何格式)的值列表。 插入之后,我需要在mysql.query调用之外公开result.insertId。 有没有办法做到这一点? (请不要问我为什么需要这样做:我知道如何解决这个问题。我只需要知道这种情况是否可行)。 理想情况下,每个数组项的描述和插入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);

我同意在console.log命令之后完成查询回调函数的Brian重新异步性质,所以没有结果。 关于查询循环,以下方法通过使其顺序化来解决。 当运行前一个查询回调时,将加载下一个数据。

问题是您不知道何时使用当前方法处理整个数组。 如果您知道最后一个循环,则可以将数组作为查询回调中的最后一步进行处理。 在此之前,您只需加载阵列。

使用迭代器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)

暂无
暂无

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

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