Node Foundation 14: Connecting to the database

Source: Internet
Author: User
Tags connection pooling

1. Connect to the database

Node itself does not have the ability to connect to the database and needs to install some intermediate libraries to support it. In this section, I'm talking about learning to connect to MySQL.

First need to install MySQL, need to go to MySQL official website download mysql, and install. Also need to install a MySQL visual management tool, this can also be downloaded on the MySQL website.

The first step:

Go to the official website to download MySQL, and install. If it is a Mac OS system, you must note the initial password () of the localhost server, and after installation, create a new database, which reminds you that you need to change the initial password. After you change the initial password, you can perform the operation of the MySQL instruction.

Step Two:

Step Three:
/** * Created by Gaoxiong on 2017/1/7.*/varMySQL = require (' MySQL ');//Create a Connect objectvarConnection =mysql.createconnection ({host:' localhost ', User:' Root ', Password:' 12345678 ', Database:' School ', Port:' 3306 '});//Connect DatabaseConnection.connect (function(err) {if(Err) {Console.log (' connect-' +err); return; } console.log (' Connected successful ');});varUseraddsql = ' INSERT into user (uname, password) VALUES (?,?) ';varparam = [' gaoxiong ', ' 123456 '];connection.query (useraddsql, param,function(err, result) {if(Err) {Console.log (' Query ', Err.message); return; } Else{Console.log (' Insert sucessful '); }}) Connection.query (' SELECT * from user ',function(err,result,fields) {if(Err) {Console.log (' Err ', Err.message); }Else{console.log (result[0]); Console.log (fields);//more Content    }})//Close ConnectConnection.end (function(err) {if(Err) {Console.log (' Close connect-' +err); return; } console.log (' Close successful ');});

The above is done to connect the database, and insert a piece of data function. It is important to note that the statements of the database query are asynchronous. The above method of connection is called direct connection, which consumes memory very much.

2. Connection Pooling Connection

First understand the concept, what is connection Pooling connection: A popular understanding, the beginning of a lot of connections (these connections make up a connection pool), when you need to take out a connection line, after the use of this cable is completed, release it, the connection line will be back to the connection pool.

This connection pool connection is also the predecessor made good Wheel (intermediate library), the name is called Node-mysql, needs the global installment.

NPM install-g Node-mysql

The code is as follows:

/** * mysqlpool.js * Created by Gaoxiong on 2017/1/7.*/varMySQL = require (' MySQL ');functionOptpool () { This. isconnected =true;  This. Pool =Mysql.createpool ({host:' localhost ', User:' Root ', Password:' 12345678 ', Database:' School ', Port:' 3306 '    });  This. Getpool =function(){        if( This. isconnected) {             This. Pool.on (' Connection ',function(connection) {Connection.query (' SET SESSION auto_increment_increment = 1 ');  This. isconnected =false; })        }        return  This. Pool; };} Module.exports= Optpool;
/** * pool.js * Created by Gaoxiong on 2017/1/7.*/varOptpool = require ('./mysqlpool '));//Create a connection poolvarOptpool =NewOptpool ();varPool =Optpool.getpool ();//get a connection from the connection poolPool.getconnection (function(ERR, conn) {Console.log (' Begin Insert '); varUseraddsql = ' INSERT into user (uname, password) VALUES (?,?) '; varPrama = [' Gaoxiong ', ' 123456 ']; Conn.query (Useraddsql, Prama,function(Err,res) {//asynchronous operation.        if(Err) {Console.log (err); return; } Else{console.log (res); Console.log (' Insert Successful ');    };    }); Console.log (' Insert End '); Console.log (' Begin SELECT ') Conn.query (' SELECT * from user ',function(Err,res) {//asynchronous operation.        if(Err) {Console.log (err); return; } Else{console.log (res[0]);        }; Conn.release ();//put back the connection pool    }); Console.log (' Select over ');});

Execute in Terminal: node Pool.js can see the effect, haha haha ah haha. Nice.

Node Foundation 14: Connecting to the database

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.