node.js mysql insert id -我如何在插入查询之外暴露插入id

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

本文关键字:插入 id 查询 暴露 mysql js insert node      更新时间:2023-09-26

假设我有一个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)