383

I've just started getting into Node.js. I come from a PHP background, so I'm fairly used to using MySQL for all my database needs.

How can I use MySQL with Node.js?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
crawf
  • 9,448
  • 10
  • 33
  • 43
  • 5
    what did you end up going with? there's some good information below, I would be interested in hearing what your experiences were – Landon Nov 14 '12 at 20:10
  • 7
    @Landon, actually went with node-mysql for a few reasons, mainly because it's in fairly active development, and seems to be the most widely used. I also really like the ````multipleStatements```` function. – crawf Nov 16 '12 at 00:35
  • @crawf What do you prefer, PHP or Node.js? I hopped into PHP/MySQL, but am thinking of switching to node since it would prolly feel much more natural considering the syntax is JS syntax – oldboy Mar 20 '18 at 19:19
  • 1
    @Anthony Personal preference I suppose, it depends on the ecosystem you're developing in, if you're in a team, etc. This original post is ancient, and a lot has changed in the Node landscape where its far more commonplace for front and back end work. I'd say if you have time to give Node a go, and its great paired with things like socket.io for real-time web sockets. – crawf Mar 21 '18 at 23:39

9 Answers9

432

Check out the node.js module list

  • node-mysql — A node.js module implementing the MySQL protocol
  • node-mysql2 — Yet another pure JS async driver. Pipelining, prepared statements.
  • node-mysql-libmysqlclient — MySQL asynchronous bindings based on libmysqlclient

node-mysql looks simple enough:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret',
});

connection.connect(function(err) {
  // connected! (unless `err` is set)
});

Queries:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  // Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
chenrui
  • 8,910
  • 3
  • 33
  • 43
mak
  • 13,267
  • 5
  • 41
  • 47
  • 81
    +1 for node-mysql actually making it _easier_ to use prepared statements than to not use them – Kevin Laity Jun 06 '11 at 21:12
  • 2
    https://github.com/bminer/node-mysql-queues for transactions and multiple statement support for use with node-mysql. – BMiner Dec 29 '11 at 22:14
  • 2
    +1 for node-mysql too. What can better than just `require`ing a javascript library – Alex K Oct 17 '12 at 11:17
  • 4
    @KevinLaity I was under the impression that node-mysql does [not yet](https://github.com/felixge/node-mysql#todo) have prepared statements implemented. The syntax just [looks similar](https://github.com/felixge/node-mysql#escaping-query-values). Instead, it appears that, for now, special characters are being escaped. – funseiki Apr 02 '13 at 21:20
  • 1
    @funseiki Hmm, I should have used the term query builder. My point was that with this syntax, you can build a safer query with minimal code. – Kevin Laity Apr 08 '13 at 19:13
  • @KevinLaity Makes sense, +1'd for the same reason (and for not having to change syntax if/when prepared statements are implemented). – funseiki Apr 08 '13 at 19:22
  • The '?' in the query always escapes the input. Important to prevent SQL-Injections - you can use the `escape` function instead to manually escape dynamic params. – user937284 Jun 03 '13 at 09:51
  • 1
    +1 for node-mysql. Also, node-mysql2 appears to be an option (link on the node-mysql-native page) for prepared statements. I'm using it now, and I notice no problems (no idea if it works correctly under the hood). – River Tam Jul 20 '13 at 19:26
  • how can we use != in query i tried "id != ?" it returns error – Sunith Saga Oct 14 '13 at 13:27
  • 4
    Plus you can get your database name adding 'database' to the connection object – felipekm Jan 27 '14 at 01:57
  • That syntax you have there isn't working for me...? it keeps on trying to perform a string replacment on the object. – GiantCowFilms Dec 24 '14 at 01:43
  • Well, the site is now updated. You'll have to search your (required) module at http://www.node-modules.com/ – Harshul Vijay Sep 15 '17 at 14:29
  • For everyone who working with mysql I suggest to use pool instead of the direct connection, you can find example code here https://stackoverflow.com/a/44230842/1078641 – electroid Feb 10 '22 at 11:41
29

node-mysql is probably one of the best modules out there used for working with MySQL database which is actively maintained and well documented.

yojimbo87
  • 65,684
  • 25
  • 123
  • 131
20

Since this is an old thread just adding an update:

To install the MySQL node.js driver:

If you run just npm install mysql, you need to be in the same directory that your run your server. I would advise to do it as in one of the following examples:

For global installation:

npm install -g mysql

For local installation:

1- Add it to your package.json in the dependencies:

"dependencies": {
    "mysql": "~2.3.2",
     ...

2- run npm install


Note that for connections to happen you will also need to be running the mysql server (which is node independent)

To install MySQL server:

There are a bunch of tutorials out there that explain this, and it is a bit dependent on operative system. Just go to google and search for how to install mysql server [Ubuntu|MacOSX|Windows]. But in a sentence: you have to go to http://www.mysql.com/downloads/ and install it.

fmsf
  • 36,317
  • 49
  • 147
  • 195
12

Here is production code which may help you.

Package.json

{
  "name": "node-mysql",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.10.6",
    "mysql": "^2.5.4"
  }
}

Here is Server file.

var express   =    require("express");
var mysql     =    require('mysql');
var app       =    express();

var pool      =    mysql.createPool({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'address_book',
    debug    :  false
});

function handle_database(req,res) {

    pool.getConnection(function(err,connection){
        if (err) {
          connection.release();
          res.json({"code" : 100, "status" : "Error in connection database"});
          return;
        }   

        console.log('connected as id ' + connection.threadId);

        connection.query("select * from user",function(err,rows){
            connection.release();
            if(!err) {
                res.json(rows);
            }           
        });

        connection.on('error', function(err) {      
              res.json({"code" : 100, "status" : "Error in connection database"});
              return;     
        });
  });
}

app.get("/",function(req,res){-
        handle_database(req,res);
});

app.listen(3000);

Reference : https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/

Shaikh Shahid
  • 1,185
  • 11
  • 13
4

KnexJs can be used as an SQL query builder in both Node.JS and the browser. I find it easy to use. Let try it - Knex.js

$ npm install knex --save
# Then add one of the following (adding a --save) flag:
$ npm install pg
$ npm install sqlite3
$ npm install mysql
$ npm install mysql2
$ npm install mariasql
$ npm install strong-oracle
$ npm install oracle
$ npm install mssql


var knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});

You can use it like this

knex.select('*').from('users')

or

knex('users').where({
  first_name: 'Test',
  last_name:  'User'
}).select('id')
Quy Tang
  • 3,929
  • 1
  • 31
  • 45
4

Imo, you should try MySQL Connector/Node.js which is the official Node.js driver for MySQL. See ref-1 and ref-2 for detailed explanation. I have tried mysqljs/mysql which is available here, but I don't find detailed documentation on classes, methods, properties of this library.

So I switched to the standard MySQL Connector/Node.js with X DevAPI, since it is an asynchronous Promise-based client library and provides good documentation. Take a look at the following code snippet :

const mysqlx = require('@mysql/xdevapi');
const rows = [];

mysqlx.getSession('mysqlx://localhost:33060')
.then(session => {
    const table = session.getSchema('testSchema').getTable('testTable');

    // The criteria is defined through the expression.
    return table.update().where('name = "bar"').set('age', 50)
        .execute()
        .then(() => {
            return table.select().orderBy('name ASC')
                .execute(row => rows.push(row));
        });
})
.then(() => {
    console.log(rows);
});
ray
  • 5,454
  • 1
  • 18
  • 40
Lex Soft
  • 2,308
  • 2
  • 13
  • 13
1

You can also try out a newer effort known as Node.js DB that aims to provide a common framework for several database engines. It is built with C++ so performance is guaranteed.

Specifically you could use its db-mysql driver for Node.js MySQL support.

Mariano Iglesias
  • 1,877
  • 1
  • 13
  • 4
  • 4
    node-db is no longer supported (inactive for 8 months, uses deprecated node-waf) and the installation failed for me. – Yogu Jan 02 '14 at 14:56
  • 18
    "It is built with C++ so performance is guaranteed" - simply using C++ does not guarantee performance, it still has to be programmed correctly. – brettwhiteman Mar 18 '15 at 06:26
  • Not only is node-db unsupported, the link is dead-ish - redirected to some kind of ad site just now. Downvoting. – nurdglaw Nov 07 '16 at 18:25
  • This is what´s wrong with the world today, idiots like this writing in forums explaining how programming works "It is built with C++ so performance is guaanteed" it´s so stupid, I just wanna cry... I´ve spent my entire life learning this busines, back i the days there were idiots of course but they was rarely heard of, now they have this gigantic fourm. Performance is guaranteed!! Is it because of the option to use malloc,is that what giarantee performance? this is a sad sad day, I sincerely hope you get out of here and never even read posts since that will turn out very wrong as well...idiot! – Patrik Forsberg Sep 16 '17 at 09:58
  • 2
    @Mariano, **Link Down** – Pacerier Nov 02 '17 at 17:59
  • The link is down because it's not supported anymore. No one should use it anymore, use the standard Node-MySQL module for most of the works now. – Boy pro Aug 22 '18 at 15:00
  • Word of warning, when I clicked the link for the Node JS DB in the post above it took me to an infected page claiming I needed to download a Flash update. So leave that link well alone... – Andy Aug 01 '19 at 14:11
0

connect the mysql database by installing a library. here, picked the stable and easy to use node-mysql module.

npm install mysql@2.0.0-alpha2

var http = require('http'),
   mysql = require('mysql');

var sqlInfo = {
   host: 'localhost',
   user: 'root',
   password: 'urpass',
   database: 'dbname'
}
client = mysql.createConnection(sqlInfo);

client.connect();

For NodeJS mysql connecting and querying example

Boris Ivanov
  • 4,145
  • 1
  • 32
  • 40
Prabin Tp
  • 758
  • 6
  • 15
  • 2
    As far as I know alpha releases are never to be concerned as 'stable'. Correct me if I'm wrong. Alpha has the possibility to dramatically change it's API before going to final which is highly unwanted in production (and even development) code. That is, if the version numbering follows the http://semver.org guidelines. – Robin van Baalen Sep 20 '13 at 13:42
  • 1
    "smart" quotes (‘’) turn out not to be that smart in js files. – 111 Aug 27 '14 at 20:28
  • I like this comment because it shows where to put database name – Boris Ivanov Nov 04 '14 at 20:42
0

You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler and sqler-mdb.

-- create this file at: db/mdb/setup/create.database.sql
CREATE DATABASE IF NOT EXISTS sqlermysql
const conf = {
  "univ": {
    "db": {
      "mdb": {
        "host": "localhost",
        "username":"admin",
        "password": "mysqlpassword"
      }
    }
  },
  "db": {
    "dialects": {
      "mdb": "sqler-mdb"
    },
    "connections": [
      {
        "id": "mdb",
        "name": "mdb",
        "dir": "db/mdb",
        "service": "MySQL",
        "dialect": "mdb",
        "pool": {},
        "driverOptions": {
          "connection": {
            "multipleStatements": true
          }
        }
      }
    ]
  }
};

// create/initialize manager
const manager = new Manager(conf);
await manager.init();

// .sql file path is path to db function
const result = await manager.db.mdb.setup.create.database();

console.log('Result:', result);

// after we're done using the manager we should close it
process.on('SIGINT', async function sigintDB() {
  await manager.close();
  console.log('Manager has been closed');
});
ugate
  • 81
  • 2