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