Hot summer, suddenly want a nodejs add MySQL, practiced hand not much explanation.
1. Install Nodejs, download the website yourself: https://nodejs.org/en/download/, double-click Run there's nothing to say.
Windows:https://nodejs.org/dist/v4.4.7/node-v4.4.7-x86.msimac:https://nodejs.org/dist/v4.4.7/node-v4.4.7.pkg
2. Create a directory + install Express+mysql
$> mkdir demolear$> cd demolear$> mkdir routes$> npm install express$ > NPM Install MySQL
Directory structure:
Demolear
|--routes
|--Mysql_route.js
|--Sample1_mysql.js
3. Code Sample1_mysql.js
varExpress = require (' Express ');varApp =Express ();//middleware or usually around here//To-dos//API RoutervarRouter =Express. Router ();varindex = require ('./routes/mysql_route ')). Router;app.use (‘/‘, index);//Start ServervarServer = App.listen (3000,function() {Console.log ("Server start at 127.0.0.1 3000");});
4. Code: Mysql_route.js
varExpress = require (' Express ');varRouter =Express. Router ();varMySQL = require (' MySQL ');varConnnectionpool =Mysql.createpool ({host:' localhost ', User:' Root ', Password:' XXXXX ', Database:' Test '}); Router.get ('/:table ',function(req, res) {//res.send (' Welcome Nodejs and Mysql ');Connnectionpool.getconnection (function(err, db) {if(Err) {Console.error (' CONNECTION error: ', err); Res.statuscode= 503; Res.send ({result:' Error ', Err:err.code}); } Else{ //Query the databaseConsole.log ("CONNECTION successful!"); //res.send ("CONNECTION successful!");Db.query (' SELECT * from ' + req.params.table,function(Err, rows, fields) {if(Err) {Console.log ("Query Data error!"); } res.send ({result:' Success ', err:‘‘, Fields:fields, Data:rows, Count:rows.length }); Db.release (); }); } });}); Module.exports.router= Router;
5. Mysql, Service: locahost, table: artical, User: root, Password: XXXXX
6. Run the command line:
$> node Sample1_mysql.js
7. Visit:
Http://localhost:3000/artical
Table name passed as URL (red word)
8. Effect:
9. Summary: The development efficiency is very fast.
node. js Connection MySQL