Node.js


MySQL integration All Versions

v0.1
v0.2
v0.3
v0.4
v0.5
v0.6
v0.7
v0.8
v0.9
v0.10
v0.11
io.js v1.0
io.js v1.1
io.js v1.2
io.js v1.3
io.js v1.4
io.js v1.5
io.js v1.6
io.js v1.7
io.js v1.8
io.js v2.0
io.js v2.1
io.js v2.2
io.js v2.3
io.js v2.4
io.js v2.5
io.js v3.0
io.js v3.1
io.js v3.2
io.js v3.3
v4.0
v4.1
v4.2
v5.0
v5.1
v5.2
v5.3
v5.4
v5.5
v0.12
v4.3
v5.6
v5.7
v4.4
v5.8
v5.9
v5.10

This draft deletes the entire topic.

inline side-by-side expand all collapse all

Examples

  • 3

    One of the easiest ways to connect to MySQL is by using mysql module. This module handle the connection between Node.JS app and MySQL server. For installing the you have to install it like any other module:

    npm install --save mysql
    

    Now, you have to create a mysql connection, that later you can query.

    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'me',
      password : 'secret',
      database : 'database_schema'
    });
    
    connection.connect();
    

    In the next example you will learn how to query the connection object

  • 1

    When you want to use user generated content in the SQL, it with done with parameters. For example for searching user with the name aminadav you should do:

    var username = 'aminadav';
    var querystring = 'SELECT name, email from users where name = ?'; 
    connection.query(querystring, [username], function(err, rows, fields) {
      if (err) throw err;
      if (rows.length) {
        rows.forEach(function(row) {
          console.log(row.name, 'email address is', row.email);
        });
      } else {
        console.log('There were no results.');
      }
    });
    
  • 1

    You send the query as string, and get a callback with the answer. The callback give your error, array of rows and fields. Each rows, contain all the column of the returned table.

    connection.query('SELECT name,email from users', function(err, rows, fields) {
      if (err) throw err;
    
      console.log('There are:', rows.length,' users);
      console.log('First user name is:',rows[0].name)
    });
    

I am downvoting this example because it is...

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have question about MySQL integration? Ask Question

Connect to MySQL

3

One of the easiest ways to connect to MySQL is by using mysql module. This module handle the connection between Node.JS app and MySQL server. For installing the you have to install it like any other module:

npm install --save mysql

Now, you have to create a mysql connection, that later you can query.

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'database_schema'
});

connection.connect();

In the next example you will learn how to query the connection object

Query a connection object with parameters

1

When you want to use user generated content in the SQL, it with done with parameters. For example for searching user with the name aminadav you should do:

var username = 'aminadav';
var querystring = 'SELECT name, email from users where name = ?'; 
connection.query(querystring, [username], function(err, rows, fields) {
  if (err) throw err;
  if (rows.length) {
    rows.forEach(function(row) {
      console.log(row.name, 'email address is', row.email);
    });
  } else {
    console.log('There were no results.');
  }
});

Query a connection object without parameters

1

You send the query as string, and get a callback with the answer. The callback give your error, array of rows and fields. Each rows, contain all the column of the returned table.

connection.query('SELECT name,email from users', function(err, rows, fields) {
  if (err) throw err;

  console.log('There are:', rows.length,' users);
  console.log('First user name is:',rows[0].name)
});

Return the query when an error occurs

0

You can attach the query executed to your err object when an error occurs:

var q = mysql.query('SELECT `name` FROM `pokedex` WHERE `id` = ?', [ 25 ], function (err, result) {
  if (err) {
    // Table 'test.pokedex' doesn't exist
    err.query = q.sql; // SELECT `name` FROM `pokedex` WHERE `id` = 25
    callback(err);
  }
  else {
    callback(null, result);
  }
});

Run a number of queries with a single connection from a pool

0

There may be situations where you have setup a pool of MySQL connections, but you have a number of queries you would like to run in sequence:

SELECT 1;
SELECT 2;

You could just run then using pool.query as seen elsewhere, however if you only have one free connection in the pool you must wait until a connection becomes available before you can run the second query.

You can, however, retain an active connection from the pool and run as many queries as you would like using a single connection using pool.getConnection:

pool.getConnection(function (err, conn) {
  if (err) return callback(err);

  conn.query('SELECT 1 AS seq', function (err, rows) {
    if (err) throw err;

    conn.query('SELECT 2 AS seq', function (err, rows) {
      if (err) throw err;

      conn.release();
      callback();
    });
  });
});

Note: You must remember to release the connection, otherwise there is one less MySQL connection available to the rest of the pool!

For more information on pooling MySQL connections check out the MySQL docs.

Using a connection pool

0

All queries in MySQL connection, are done one after another. It mean that if you want to do 10 queries, and each query takes 2 seconds, it will take 20 seconds to complete. The solution is to create 10 connection and run each query in a different connection. This can be done automatically using connection pool

var pool  = mysql.createPool({
  connectionLimit : 10,
  host            : 'example.org',
  user            : 'bobby',
  password        : 'pass',
  database        : 'schema'
});

for(var i=0;i<10;i++){
  pool.query('SELECT ` as example', function(err, rows, fields) {
    if (err) throw err;
    console.log(rows[0].example); //Show 1
  });
 }

It will run all the 10 queries in parallel.

When you use pool you don't need the connection any more. You can query directly the pool. MySQL module will search for the next free connection to execute your query.

Topic Outline