在Express中连接到数据库

时间:2013-08-09 14:37:26

标签: node.js express

尝试使用Express

连接到数据库
  • 我是Express的新手(我使用过NODEJS),
  • 我正在尝试连接到数据库并显示一个简单的JSON作为 结果输出
  • 我尝试了以下代码

var express = require('express')
  , http = require('http');

var app = express();

var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: "root",
        database: 'restaurant'
});

// all environments
app.set('port', process.env.PORT || 7002);


app.get('/',function(request,response){
connection.query('SELECT * FROM restaurants', function(err, rows, fields)

        {
                console.log('Connection result error '+err);
                console.log('no of records is '+rows.length);
                        response.writeHead(200, { 'Content-Type': 'application/json'});
                response.end(JSON.stringify(rows));
        });

} );

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

错误::

var connection = mysql.createConnection({
                 ^
ReferenceError: mysql is not defined

错误告诉mysql模块不存在,但是我已经使用::

安装了mysql模块
npm install mysql 

错误仍未改变 任何想法

1 个答案:

答案 0 :(得分:2)

您错过了mysql模块。

var express = require('express')
  , http = require('http')
  , mysql = require('mysql');

但您还需要connect()

connection.connect();

开始查询数据库之前。

现在为懒惰加起来:

var express = require('express')
  , http = require('http')
  , mysql = require('mysql'); // <---- HERE

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: "root",
    database: 'restaurant'
});

connection.connect(); // <---- AND HERE

// all environments
app.set('port', process.env.PORT || 7002);


app.get('/',function(request,response){
connection.query('SELECT * FROM restaurants', function(err, rows, fields)

    {
            console.log('Connection result error '+err);
            console.log('no of records is '+rows.length);
                    response.writeHead(200, { 'Content-Type': 'application/json'});
            response.end(JSON.stringify(rows));
    });

} );

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});