How do I connect MariaDB to Node.JS and Express.JS?
Asked Answered
T

2

7

I'm doing Colt Steele's The Web Developer Bootcamp and I've got to the point where we're going to start a database for the YelpCamp app. Problem is, he is using MongoDB, and I don't want to use that. I want to use MariaDB. How can I get Node JS to work with it? I've already added it to my project using npm install, but I've got no idea where to go from here. I can't find any guides pertaining specifically to nodejs and mariadb. The official guide is not beginner friendly. I have no idea what alot of it even says.

I'm not working thorugh Cloud9 like he is because they're not accepting new registrations. I am running node.js on my computer using the command line, and have been following his videos that way.

Tulley answered 24/8, 2018 at 1:6 Comment(0)
G
8

https://github.com/MariaDB/mariadb-connector-nodejs

Install: npm i mariadb

const mariadb = require('mariadb');
const pool = mariadb.createPool({host: 'mydb.com', user: 'myUser', connectionLimit: 5});
pool.getConnection()
    .then(conn => {
      conn.query("SELECT 1 as val")
        .then((rows) => {
          console.log(rows); //[ {val: 1}, meta: ... ]
          return conn.query("INSERT INTO myTable value (?, ?)", [1, "mariadb"]);
        })
        .then((res) => {
          console.log(res); // { affectedRows: 1, insertId: 1, warningStatus: 0 }
          conn.end();
        })
        .catch(err => {
          //handle error
          conn.end();
        })
    }).catch(err => {
      //not connected
    });
Guarino answered 24/8, 2018 at 7:19 Comment(2)
How you select database in your example?Latour
Just add database: 'your_database' to the createConnection call. You can find all the options here: mariadb.com/kb/en/library/nodejs-connection-optionsGuarino
P
3

Sequelize

npm install --save sequelize@next
npm install --save mariadb

Then set dialect: 'mariadb'

The mariadb connector is much faster than MySQL2. I noticed the speed difference immediately on my platform.

https://github.com/MariaDB/mariadb-connector-nodejs

MariaDB provides benchmarks comparing the Connector with popular Node.js MySQL clients, including:

promise-mysql version 3.3.1 + mysql version 2.15.0 mysql2 version 1.5.3

promise-mysql  : 1,366 ops/sec ±1.42%
mysql2         : 1,469 ops/sec ±1.63%
mariadb        : 1,802 ops/sec ±1.19%
Pavkovic answered 17/12, 2018 at 6:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.