1. Run the NPM install MySQL module for NODEJS in the project directory;
2. Create db.js module to connect MySQL and define query method;
varMySQL = require (' MySQL ');//Create a database connection poolvarPool =Mysql.createpool ({connectionlimit:50, Host:' localhost ', User:' Admin ', Password:' 123456 ', Database:' Rp-test '});//SELECT * from Users//Let our approach support two modes//one is to pass in only SQL statements and callback functions//one is the incoming SQL statement, the parameter data, the callback functionExports.query=function(SQL, P, C) {varparams = []; varcallback; //If the user passes in two parameters, SQL and callback if(Arguments.length = = 2 &&typeofARGUMENTS[1] = = ' function ') {Callback=P; } Else if(Arguments.length = = 3 && array.isarray (arguments[1]) &&typeofARGUMENTS[2] = = ' function ') {params=P; Callback=C; } Else { Throw NewError (' Sorry, parameter number mismatch or parameter type error ')); } //If the user passes in three parameters, it is the SQL and the parameter array, the callback function //get a connection from the pool that you can use.Pool.getconnection (function(err, connection) {//Use the connectionConnection.query (SQL, params,function () { //after use is complete, release the connection back to the connection poolconnection.release (); Callback.apply (NULL, arguments); }); });};
3. Query Example
var express = require (' Express '); var db = require ('./db '); var router = Express. Router (); Router.get ('/',function(req, res, next) { db.query ("select * from App", function(err,result) { //console.log (result); res.send (json.stringify (Result));}) ; Module.exports=router;
Nodejs connecting MySQL instances