很少有以前的答案可以帮助你
Express.JS + Node-Mysql 和每个 http 请求 1 个连接
如何在nodejs中启动http服务器之前查询mysql
从 db 获取简单信息到 node.js http 服务器响应
在 mysql
Node.js MySQL 中使用池需要持久连接
一个更复杂的解决方案将您的代码分成文件并将数据库代码放在 db.js 或响应处理程序或路由器中。
我的代码正在使用池。
保存到五个文件然后运行 npm install
例如(请原谅可怕的格式)
// requestHandlers.js
// request handler with mysql code
var mysql = require("mysql");
var Query1 = "SELECT * from Tablexyz WHERE xx = 'doh'";
var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<h1> Query </h1>';
var body1 = '</body>'+
'</html>';
var pool = mysql.createPool({
host : 'host',
user : 'dbuser',
password : "pword",
database : 'database',
connectionLimit: 10,
queueLimit: 10
});
function qquery(callback){
console.log('in qquery');
pool.getConnection(function(err, connection) {
pool.query( Query1 , function(err, rows ,fields) {
if (err) {
return callback(new Error("An error has occured" + err));
}
if (rows.length > 0){
callback( rows);
connection.release();
}
});
});
}
function start(response) {
console.log("Request handler 'start' was called.");
qquery( function (rows , err) {
if (err) {
console.log(err);
}
else{
console.log(rows);
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.write( 'query: ' + JSON.stringify( rows ) );
response.write(body1);
response.end();
}
});
}
出口.开始=开始;
///////////////////////////////////- new file
//server.js
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
///////////////////////////////////-new file
// router.js
function route(handle, pathname, response) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
///////////////////////////////////- new file
//index.js
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
///////////////////////////////////- new file
//package.json
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies":
{
"express": "3.4.0",
"jade": "*",
"stylus": "*",
"mysql": "*"
}
}