![](/img/trans.png)
[英]get the last insert id in node.js and pass it to a second query
[英]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.