Node. js connects to the database
Before Connecting Node. js to the database, you need to install the corresponding package. If you want to install SQL server, You Need To package node-sqlserver first. We use mysql as an example to illustrate how node. js queries mysql Data.
1. Install node-mysql
Npm install node-mysql
2. database connection through the express framework
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: 'ceshi', password: '000000', port: 123456}); conn. connect (); app. get ('/', function (req, res) {conn. query ('select * from ceshibiao ', function (err, rows, fields) {if (err) throw err; var data = ''; foreach (rows, function (key, value) {data + =''+ 'Contents:' + value. contents +'
'; Data + ='
';}Res. send (data) ;}); app. listen (81); console. log ('listening on port 81 ');