Home > Database > Mysql Tutorial > NodeJs连接Mysql数据库

NodeJs连接Mysql数据库

WBOY
Release: 2016-06-07 15:01:27
Original
1018 people have browsed it

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 安装node-mysql: npm install mysql@2.0.0-alpha9 npm install node-mysql node程序启动文件app.js: var express = require('express'); var mysql = require('mysql'); var app = express()

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

  安装node-mysql:

  npm install mysql@2.0.0-alpha9

  npm install node-mysql

  node程序启动文件app.js:

  var express = require('express');

  var mysql = require('mysql');

  var app = express();

  app.use(function(req, res, next){

  console.log('%s %s', req.method, req.url);

  next();

  });

  var conn = mysql.createConnection({

  host:'localhost',

  user:'root',

  database:'nodedb',

  password:'********',

  port:3306

  });

  conn.connect();

  app.get('/', function(req, res){

  conn.query('SELECT * from news', function(err, rows, fields) {

  if (err) throw err;

  var data = '';

  for(var i = 0; i

  data += '

' + 'ID:' + rows[i].id + '

';

  data += '

' + 'title:' + rows[i].title + '

';

  data += '

' + 'contents:' + rows[i].contents + '

';

  data += '


';

  }

  res.send(data);

  });

  });

  app.listen(3000);

  console.log('Listening on port 3000');

NodeJs连接Mysql数据库

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template