如何在 NodeJS 中创建查询 MySQL 的函数?

How to make a function to query MySQL in NodeJS?

我做了这个:

const mysql = require('mysql2/promise')

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'nodejs',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
})

async function query(query) {

    const result = await pool.query(query)
    return result[0]

}

console.log(query('SELECT * FROM `users`'))

我回来了

Promise { <pending> }

如何从查询数据库中取回结果,就像 PHP 一样?
在 PHP 我从来没有做过像 async/await 这样的事情并承诺...

我也尝试使用 mysql:

const mysql = require('mysql')

const db = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'nodejs'
})

function query(query) {
    db.query(query, (err, result) => {
        if (err) throw err
        return result
    })
}

console.log(query('SELECT * FROM `users`'))

但我得到了一个未定义的结果

我对 MySQL 和您使用的库不是很熟悉。

但是,您收到的 Promise { <pending> } 响应是因为您没有等待查询执行。

由于该函数被标记为 async 并且还在执行异步操作,因此它 returns 需要等待解决的 Promise。

下面的代码应该可以工作:

const mysql = require('mysql2/promise')

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'nodejs',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
})

async function query(query) {

    const result = await pool.query(query)
    return result[0]

}

(async () => {
    const queryResult = await query('SELECT * FROM `users`');
    console.log(queryResult);
} )();

要了解 async-await 的工作原理,请考虑以下代码:

console.log('I will get printed first');
const asyncFunction = async () => {
   await setTimeout(()=> {}, 1000)
   console.log('I will get printed third');
   return 'hello'
}

(async () => {
  const result = await asyncFunction();
  console.log(`I will get printed last with result: ${result}`);
})();

console.log('I will get printed second');

console.log 语句 I will get printed last with result 将等待 asyncFunction 完成执行后才执行。

试试这个:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

试试这个:

var mysql = require('mysql');

var con = mysql.createConnection({
    host: "localhost",
    user: "yourusername",
    password: "yourpassword",
    database: "mydb"
});

// function definition
function runQuery (con, sqlQuery) {

    return new Promise((resolve, reject) => {
        console.log("START");
        if(con){
            con.connect(function (err) {
                if (err) throw err;
            });

            if (sqlQuery) {
                con.query(sqlQuery, function (error, result, fields) {
                    connection.end(); // end connection
                    if (error) {
                        throw error;
                    } else {
                        return resolve(result);
                    }
                });
            } else {
                connection.end(); // end connection
                // code:  handle the case 
            }
        } else {
            // code: handle the case
        }

    });

}

var sqlQuery = 'SELECT * FROM tableName';

// function call and pass the connection and sql query you want to execute
var p  = runQuery(con, sqlQuery); 
p.then((data)=>{ // promise and callback function
    console.log('data :', data); // result
    console.log("END");

});