简体   繁体   English

NodeJS mysql connection.query 回调未将结果记录到控制台?

[英]NodeJS mysql connection.query callback not logging results to console?

Trying to use the mySQL npm package to connect to a database and print the results of queries.尝试使用 mySQL npm 包连接到数据库并打印查询结果。 Why do the console.log() statements within con.connect() and con.query() not print 'connected!'为什么 con.connect() 和 con.query() 中的 console.log() 语句不打印“已连接!” or the results of the query to the console?或查询到控制台的结果?

The console.log("we here now") gets executed and the program does not exit. console.log("we here now") 被执行并且程序不会退出。 If I supply a wrong password/host the error within con.connect() does get thrown but when the connection is established, "connected!"如果我提供了错误的密码/主机,则 con.connect() 中的错误确实会被抛出,但是当建立连接时,“已连接!” isn't printed.没有打印。 What am I missing?我错过了什么?

var mysql = require('mysql');

var con = mysql.createConnection({
    host: 'host',
    port: 'port',
    user: 'user',
    password: 'pass'
});


con.connect(function(err) {
    if (err) throw err;
    console.log("connected!");
    con.query("SELECT 1 as solution", function (err, result, fields) {
        if (err) throw err;
        console.log(result);
    });
});

console.log("we here now");

con.end();

1- Have you correctly changed these 4 variable 1- 您是否正确更改了这 4 个变量

host: 'host', port: 'port', user: 'user', password: 'pass'主机:'host',端口:'port',用户:'user',密码:'pass'

2- Make sure that your mysql DB server is running 2- 确保您的 mysql 数据库服务器正在运行

3- Verify your SQL SELECT Query, what is 1 and from which table ? 3- 验证您的 SQL SELECT 查询,什么是 1,来自哪个表? and make sure that the DB is not empty.并确保数据库不为空。

Use the following code in server.js file在 server.js 文件中使用以下代码

var mysql = require('mysql');
const util = require('util');

        const mysqlconnection = mysql.createConnection({
            host: '10.0.1.117', //Change this IP
            user: 'john',
            password: 'password',
            database: 'customers_db',
            port: 3306,
            multipleStatements: true,
        });
          
      

const db1 = mysqlconnection;
const query = util.promisify(db1.query).bind(db1);


async function connectMySql(callback) {
    mysqlconnection.connect(async function (err, client) {
        if (err) {
            console.error('error connecting: ' + err);
            return;
        }
        let myquery1 = "SELECT * FROM users";
        var newRecords = [];
        newRecords = await query(myquery1)
            .catch(err => {
                console.log(err)
            });
        console.log(newRecords)
    });
};

connectMySql();

This gives output as这给出了输出

> [ RowDataPacket {
>     UserId: 101212,
>     LoginName: 'user1233',
>     RoleName: user',
>     C7: '2021-07-28 11:29:28' } ]

So a few things.所以有几件事。

First, a slight refactor.首先,稍微重构一下。 Move the connection.query to the same scope as the connect invocation.connection.query移动到与connect调用相同的范围。

Make sure you set the connection config of course:确保您设置了连接配置:

const mysql      = require('mysql');
const connection = mysql.createConnection({
  host     : 'BE_SURE_TO_SET_ME',
  user     : 'BE_SURE_TO_SET_ME',
  password : 'BE_SURE_TO_SET_ME',
  database : 'BE_SURE_TO_SET_ME'
});

connection.connect(function(error){
  if (error) {
    console.error('❌ Query failed: ', error);
    throw error;
  }
  console.log('✅ Connection successful');
});

connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) {
    console.error('❌ Query failed: ', error);
    throw error;
  }
  console.log('✅ Query successful. Results: ', {results});
});

connection.end();

Secondly, JS is async by nature, so the reason console.log("we here now");其次,JS 本质上是异步的,所以console.log("we here now"); fires is because it is in the same scope as connect . fires 是因为它与connect处于同一范围内。 The JS engine won't wait until the connect callback is called, it just moves to the next statement. JS 引擎不会等到 connect 回调被调用,它只是移动到下一个语句。 So there's a race condition - it may (or may not) be executed on the process tick before the connect function callback throws an error.因此存在竞争条件 - 在连接函数回调引发错误之前,它可能(或可能不会)在进程滴答上执行。

Accordingly, I have added console.log and console.error statements in the callbacks where they occur.因此,我在它们发生的回调中添加了console.logconsole.error语句。 This will give you better feedback.这会给你更好的反馈。 (ps. better to use a logger like winston ) (ps。最好使用像winston这样的记录器)

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

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