Connect to MySQL using node

Source: Internet
Author: User

Installing dependent libraries

NPM install MySQL

Create a database connection

var mysql = require (' mysql '); Define connection parameters var Mysqlconn = {host: ' 127.0.0.1 ', User: ' User ', Password: ' Password ', database: ' Nodejs ', Port: ' 3306 '}; Create connection var conn = mysql.createconnection (mysqlconn); Conn.connect (); Execute SQL Conn.query (' Select Solution ', function (err,rows,fields) {if (err) {throw err;} console.log (' Select result I S ' + rows[0].so); })//close connection? Conn.end ();

Using a database connection pool

var mysql = require (' mysql '); var mysqlconn = {host: ' 127.0.0.1 ', User: ' Root ', password: ' jt123456 ', database: ' Nodejs ', Port: ' 3306 '}; var pool = Mysql.createpool (mysqlconn);//Get connectionpool.getconnection from Connection pool (function (err,conn) {if (err) { Console.log (' Err when getconnection from pool: ' +err);} Conn.query (' Select Solution ', function (err,rows) {if (err) {Consloe.log (' err when query sql: ' +err ');} Console.log (' solution is ' +rows[0].solution);//release current connectionconn.release ();});

Exceptions when processing a connection

var mysql = require (' mysql '); var mysqlconn = {host: ' 127.0.0.1 ', User: ' Root ', password: ' jt123456 ', database: ' Nodejs ', Port: ' 3306 '};//re-connect function hand Leerror () {var conn = mysql.createconnection (mysqlconn);//error printing when connecting, and reconnection Conn.connect after 2 seconds (function (err) {if (err) { Console.log (' Err when connect with MySQL server: ' +err);}; SetTimeout (handleerror,2000);}); /Listen for exceptions in the connection Conn.on (' Error ', function (err) {Console.log (' err: ' +err);//automatically reconnect if when disconnected (err.code = = = ' Protocol_connection_ LOST ') {handleError ();} Else{throw err;}});} Handleeror ();

Reference: Connecting MySQL with Nodejs

Connect to MySQL using node

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.