SELECT 在 node.js 中不起作用 [英] SELECT not working in node.js

查看:74
本文介绍了SELECT 在 node.js 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 node.js 在我的 SQL 数据库上使用 SELECT 查询,下面的 SELECT 查询应该可以工作,但没有.这很奇怪,因为我认为这应该可行,但它甚至没有进入 client.query 函数.我还复制了我的 INSERT 查询,它实际上正在向您展示我与数据库的连接工作正常.

I'm trying to use a SELECT query on my SQL database using node.js, the SELECT query below should work but doesn't. This is weird because I think this should work but it doesn't even enter the client.query function. I also copied my INSERT query which is actually working to show you my connection to the database works fine.

我在 SELECT 查询中做错了什么?

What am I doing wrong in the SELECT query?

创建连接

var mysql = require('mysql');
var client = mysql.createConnection({
    host: '***',
    user: '***',
    password: '***',
    database: '***'
});

SELECT 查询(不工作)

SELECT Query (Not working)

    function query(sql){
      var returnvalue = "tempVal";
      client.connect();
      client.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
        returnvalue = "doens't even enter function";
        if (err) throw err;

        returnvalue = rows[0].solution;
      });
      client.end();    
      return returnvalue;
    }

插入查询(正在运行)

function query(sql){
  client.connect();
  client.query('INSERT INTO users (username) VALUES("foo")');
  client.end();
}

推荐答案

由于 .query() 是一个异步方法,您将无法返回值作为回调将被调用之后 return 被评估.

As .query() is an asynchronous method, you won't be able to return the value as the callback will be called after the return is evaluated.

您必须继续使用 callback 模式:

You'll have to continue the callback pattern:

function query(sql, callback) {
    client.connect();
    client.query(sql, function (err, rows, fields) {
        if (err) {
            callback(err);
        else
            callback(null, rows, fields);
    });

    client.end();
}

更正:似乎 client.end() 将允许在连接实际关闭之前完成当前查询.

Correction: Seems client.end() will allow current queries to finish before the connection actually closes.

使用 end() 关闭连接,确保在向 mysql 服务器发送退出数据包之前执行所有剩余的查询.

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

不过,在回调中调用 .end() 对许多 API 来说是司空见惯的,因为它们会切断任何挂起的操作.

Though, calling .end() inside the callback is commonplace for many APIs as they will cut-off any pending actions.

这篇关于SELECT 在 node.js 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆