Thinking about Nodejs access to MySQL

Source: Internet
Author: User

Nodejs to access the MySQL database, you must first install the package mysql, command: npm install MySQL. After successful installation, the following database code is accessed:

varMySQL = require (' MySQL ');varOptions ={host:' 172.23.88.107 ', Port:3306, Database:' Test ', User:' Root ', Password:' Zdsoft '};varPool =mysql.createpool (options);p ool.getconnection (function(ERR, conn) {if(Err) {Console.log (err);//Printing error Messages}Else{conn.query ("SELECT * FROM Student",NULL,function(Err, results, fields) {//Release Connectionconn.release (); if(Err) {Console.log (err); } Else{Console.log (results);//successful, print result set            }        })    }});

OK, the above code has been tested there is no problem, but now there is a problem, every time we access the database is written so large a feeling too tired, so we want to extract the public part to create a class, the file name is: Sqlhelper.js. Since database access is asynchronous, we cannot directly return by returning it, so we have to use the callback function, and the Sqlhelper.js code is as follows:

varMySQL = require (' MySQL ');varOptions ={host:' 172.23.88.107 ', Port:3306, Database:' Test ', User:' Root ', Password:' Zdsoft '};varPool =mysql.createpool (options); Exports.query=function(SQL, Vals, fn) {pool.getconnection (function(ERR, conn) {if(Err) {fn (NewError (err)); } Else{conn.query (SQL,NULL,function(Err, results, fields) {//Release Connectionconn.release (); if(Err) {fn (NewError (err)); } Else{fn (NULL, results, fields); }            })        }    });}

In this way, we can directly pass the call to the FN callback function, the method is called as follows:

var mysql = require ('./lib/sqlhelper.js '); // sqlhelper.js file below the Lib folder var NULL function (Err, results, fields) {    if  (results) {        for (Let index = 0; index < res Ults.length; index++) {            console.log (results[index].name);        }     Else {        console.log ("err,msg:" + err);    });

Since then, we have also been the most accomplished.

================================================ Split Line ===========================================================

However, we have another way to achieve this, through the Promise object, through the Promise object we can write the same as the synchronous program to write asynchronous code, so do not have to go to an infinite number of nested callback functions, Sqlhelper.js modified as follows:

varMySQL = require (' MySQL ');varOptions ={host:' 172.23.88.107 ', Port:3306, Database:' Test ', User:' Root ', Password:' Zdsoft '};varPool =mysql.createpool (options); Exports.query=function(SQL) {return NewPromise (function(Resolve, Reject) {pool.getconnection (function(ERR, conn) {if(Err) {reject (err);//let the state become defunct and pass the error message back}Else{conn.query (SQL,NULL,function(Err, results, fields) {//Release Connectionconn.release (); if(Err) {reject (err); } Else{Resolve (results, fields);//let the state become successful and pass the success data back                    }                })            }        }); });}

The calling method is modified as follows:

var mysql = require ('./lib/sqlhelper.js '); // sqlhelper.js file below the Lib folder var promise = Mysql.query ("SELECT * from Student");p romise.then (function  (results, Fields) {    for (Let index = 0; index < results.length; index++) {        Console.log (results[ Index].name);     function (Err) {    console.log (err);});

As you can see, we're not using a callback function anymore.

Thinking about Nodejs access to MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.