-1

所以我有下一个测试代码,我在这里找到了

// Include http module,
var http = require('http'),
// And mysql module you've just installed.
   mysql = require("mysql");
// Create the connection.
// Data is default to new mysql installation and should be changed according to your configuration.
var connection = mysql.createConnection({
   user: "root",
   password: "pass",
   database: "db_name"
});
// Create the http server.
http.createServer(function (request, response) {
   // Attach listener on end event.
   request.on('end', function () {
      // Query the database.
      connection.query('SELECT * FROM your_table;', function (error, rows, fields) {
         response.writeHead(200, {
            'Content-Type': 'x-application/json'
         });
         // Send data as JSON string.
         // Rows variable holds the result of the query.
         response.end(JSON.stringify(rows));
      });
   });
// Listen on the 8080 port.
}).listen(8080);

我下载了 mysql 模块,当然安装了 mysql,然后运行下一个脚本,但没有得到任何结果。你能给我建议我做错了什么吗?

当我试图加载

http://localhost:8080/

浏览器尝试加载页面几分钟,也没有结果。

谢谢。

更新 在此处输入图像描述

4

3 回答 3

2

我想你忘记了

connection.connect()

我现在正在使用这些,它对我来说很好。

// Include http module,
var http = require('http'),
// And mysql module you've just installed.
   mysql = require("mysql");
// Create the connection.
// Data is default to new mysql installation and should be changed according to your configuration.
var connection = mysql.createConnection({
   host: "localhost",
   user: "root",
   password: "pass",
   database: "db_name"
});
connection.connect();
// Create the http server.
http.createServer(function (request, response) {
   // Attach listener on end event.
   request.on('end', function () {
      // Query the database.
      connection.query('SELECT * FROM your_table;', function (error, rows, fields) {
         response.writeHead(200, {
            'Content-Type': 'x-application/json'
         });
         // Send data as JSON string.
         // Rows variable holds the result of the query.
         response.end(JSON.stringify(rows));
      });
   });
// Listen on the 8080 port.
}).listen(8080);
于 2012-10-15T12:01:28.517 回答
0

@石川耀西

使用回调

// Include http module
var http = require('http')
// And mysql module you've just installed.
 mysql = require("mysql");

 var Query1 = "SELECT * from Tablexyz WHERE xx = 'doh'";

   var connection = mysql.createConnection({
    host     : 'host',
    user     : 'dbuser',
    password : "pword",
    database : 'database',
    });

   connection.connect();

   function getData(callback){
   console.log('in getData');
    connection.query( Query1 , function(err, rows ,fields) {
    if (err) {
        return callback(new Error("An error has occured" + err));
    }
    if (rows.length > 0){
        callback( rows);
    }

});
}

// Create the http server.
http.createServer(function (request, response) {
// Attach listener on end event.

  // Query the database.
 getData(function (rows , err) {
    if (err) {
       console.log(err);
    }
     else{
         response.writeHead(200, {"Content-Type": "text/html"});
         response.write( 'query: ' + JSON.stringify( rows ) );
         response.end();
     }
});
   // Listen on the 4001 port.
   }).listen(4001);
于 2013-10-23T06:40:13.757 回答
0

很少有以前的答案可以帮助你

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": "*"
     }

}

于 2013-10-23T06:22:30.207 回答