簡體   English   中英

如何使用 Node.js (mysql2) 從 SQL 返回數據

[英]How to return data from SQL with Node.js (mysql2)

我將我的代碼從 Python 重寫為 Node.js 我需要從 SQL 中獲取一些數據,然后在代碼中使用它。 所以用python很容易,你只要得到它,返回就可以使用它。

Python中的代碼

def sql_get_new_id(connection):

    with connection.cursor() as cursor:

    sql = "SELECT * FROM `item` WHERE 1"
    cursor.execute(sql)
    result = cursor.fetchall()

    return len(result)  # <==== So you just can get this data and use it out of the loop
 
print(sql_get_new_id()) # <==== Right here it works perfectly

但是在 JS 中,正如我所見,我不能只在函數末尾返回它。 您只能在控制台上看到它。 那我現在怎么得到呢?

const mysql = require("mysql2");
 
const sql = `SELECT * FROM item WHERE 1`;
 
connection.query(sql, function(err, results) {
    if(err) console.log(err);
    console.log(results.length);  // <===== I can do a console log
    return results.length;  // <====== But returning doesn't let me use it out of the loop
});
 
connection.end();
}

console.log(sqlGetNewId())  // <==== There is no data i need

在函數中而不是控制台日志中,您可以輸入:return results.lengtg;

如果那是你想做的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM