MariaDB: Using MariaDB with Node.js
This documentation is part of the Getting started guide. View the full guide here: How to get started with MariaDB.
👋 Welcome to Stackhero documentation
Stackhero provides a ready-to-use MariaDB cloud service designed for production workloads. You get:
- Unlimited connections and data transfers.
- Built-in phpMyAdmin web interface for database management.
- One-click updates for easy maintenance.
- High performance and strong security on private, dedicated infrastructure.
Launch a fully managed MariaDB instance in minutes. Stackhero handles setup, updates, and security so you can focus on your application. Learn more about MariaDB cloud hosting.
If you are using Node.js, you can try the mysql2 package, which has promise support. To install it:
npm install mysql2
Here is an example you can adapt:
const mysql = require('mysql2/promise');
(async () => {
const db = await mysql.createConnection({
host: '<XXXXXX>.stackhero-network.com',
port: '<PORT>',
user: 'root',
password: '<ROOT_PASSWORD>'
});
// Create a database if it does not already exist
await db.query('CREATE DATABASE IF NOT EXISTS stackherotest');
// Create the users table if it does not exist
await db.query(
'CREATE TABLE IF NOT EXISTS `stackherotest`.`users` (' +
'`userId` INT UNSIGNED NOT NULL,' +
'`name` VARCHAR(128) NOT NULL,' +
'`address` TEXT NOT NULL,' +
'`email` VARCHAR(265) NOT NULL' +
') ENGINE = InnoDB;'
);
// Insert a sample user
await db.query(
'INSERT INTO `stackherotest`.`users` (`userId`, `name`, `address`, `email`) VALUES ?',
[
[
Math.round(Math.random() * 100000), // Generate a userId
'User name', // name
'User address', // address
'[email protected]' // email
]
]
);
// Count users in the table
const [usersCount] = await db.query('SELECT COUNT(*) AS `cpt` FROM `stackherotest`.`users`');
console.log(`There are now ${usersCount[0].cpt} entries in the table "users"`);
// Close the connection
await db.end();
})().catch(error => {
console.error('');
console.error('An error occurred!');
console.error(error);
process.exit(1);
});