无法使用 mysql 模块在 node.js 中执行 Sql 查询 [英] Unable to execute Sql query in node.js using mysql module

查看:29
本文介绍了无法使用 mysql 模块在 node.js 中执行 Sql 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的 app.js 文件内容.当我尝试在节点中执行此操作时,我收到执行查询时出错."虽然该表包含 5 行,但似乎仍有一些错误.请让我知道我哪里做错了

Below is my app.js file content. When i try to execute this in node i am getting "Error while performing Query." Although this table contains 5 rows but still something seems to be wrong. Please let me know where i am doing wrong

app.js

var express = require('express');
var mysql = require('mysql');
var app = express();
var port = process.env.PORT || 8081;

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "mydata"
});

con.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});

app.get("/",function(req,res){
  con.query("select * from club_data ", function(err, rows,field) {
  if (!err)
  {
    console.log('The solution is: ', rows);
   }
  else
    console.log('Error while performing Query.');
  });
});



con.end(function(err) {
  // The connection is terminated gracefully
  // Ensures all previously enqueued queries are still
  // before sending a COM_QUIT packet to the MySQL server.
});

// START THE SERVER
// =============================================================================
app.listen(port);

服务器输出:

PS C:\Users\skull_king\Desktop\Workspace> node .\app.js
Connection established
Error while performing Query.

推荐答案

请记住,Node.JS 主要是异步.您使用 app.get(...) 声明的请求处理程序不会立即执行,而是会在收到第一个(或任何)请求时稍后执行.

Remember that Node.JS is mostly asynchronous. The request handler that you declare with app.get(...) is not executed immediately, but only later, when the first (or any) request is received.

在声明请求处理程序之后,您会立即关闭 MySQL 连接,甚至在第一个请求被处理之前就使用 con.end(...) 调用.当您尝试处理请求时,con 已经关闭,因为您之前已使用 con.end 关闭它.

Immediately after declaring the request handler, you're closing the MySQL connection with the con.end(...) call even before the first request is handled. When you're trying to handle the request, con is already closed, because you have closed it with con.end before.

您可能想要实现的是在服务器关闭时关闭 MySQL 连接.为此,您可以监听服务器的 close 事件(但未经测试):

What you are probably trying to achieve is to close the MySQL connection when the server shuts down. For that, you could listen on the server's close event (untested, though):

app.on('close', function() {
    con.end();
});

这篇关于无法使用 mysql 模块在 node.js 中执行 Sql 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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