A Beginner's Guide to Using MariaDB with JavaScript and Node.js

In this guide, we’ll walk you through the basic usage of MariaDB within a JavaScript/Node.js application.

Posted on

MariaDB is a robust, open-source relational database management system (RDBMS) that’s known for its speed, reliability, and feature set. If you’re building applications with JavaScript and Node.js, MariaDB can be an excellent choice for managing your data. In this guide, we’ll walk you through the basic usage of MariaDB within a JavaScript/Node.js application.

Prerequisites

Before we get started, ensure you have the following prerequisites in place:

  1. Node.js: You should have Node.js installed on your system. You can download it from the official website nodejs.org.

  2. MariaDB: Make sure MariaDB is installed on your system. If not, you can obtain it from the MariaDB website.

  3. MariaDB Client Library: You’ll need a MariaDB client library to establish a connection between your Node.js application and the database. One popular choice is the mysql2 library, which can be installed using npm:

    npm install mysql2
    

Setting up a MariaDB Connection

To interact with MariaDB from your Node.js application, the first step is establishing a connection to the database. Below is a sample code snippet demonstrating how to set up a connection using the mysql2 library:

const mysql = require("mysql2")

// Create a connection pool
const pool = mysql.createPool({
  host: "localhost", // Replace with your database host
  user: "username", // Replace with your database username
  password: "password", // Replace with your database password
  database: "mydb" // Replace with your database name
})

// Get a connection from the pool
pool.getConnection((err, connection) => {
  if (err) {
    console.error("Error connecting to MariaDB:", err)
    return
  }

  console.log("Connected to MariaDB!")

  // Use the connection for database operations

  // Release the connection when done
  connection.release()
})

Remember to replace the connection details with your specific database credentials.

Performing Basic Database Operations

Once you’ve successfully established a connection, you can start performing various database operations such as querying, inserting, updating, and deleting data. Below are examples of each operation with accompanying comments and explanations.

Querying Data

// Introduction: Fetching data from the 'users' table.
pool.query("SELECT * FROM users", (err, results) => {
  if (err) {
    console.error("Error querying the database:", err)
    return
  }

  // 'results' contains the rows retrieved from the database
  console.log("Query results:", results)
})

After executing the SELECT query, the results variable will contain an array of rows retrieved from the ‘users’ table.

Inserting Data

// Introduction: Adding a new user to the 'users' table.
const newUser = { username: "john_doe", email: "[email protected]" }

pool.query("INSERT INTO users SET ?", newUser, (err, results) => {
  if (err) {
    console.error("Error inserting data:", err)
    return
  }

  // 'results' may contain information about the inserted row
  console.log("Data inserted successfully!")
})

Upon executing the INSERT query, a new user with the specified data will be added to the ‘users’ table in the database.

Updating Data

// Introduction: Updating a specific user's email in the 'users' table.
const updatedUser = { email: "[email protected]" }

pool.query(
  "UPDATE users SET ? WHERE username = ?",
  [updatedUser, "john_doe"],
  (err, results) => {
    if (err) {
      console.error("Error updating data:", err)
      return
    }

    // 'results' may contain information about the updated row
    console.log("Data updated successfully!")
  }
)

Executing the UPDATE query will modify the email of a specific user in the ‘users’ table to the new value specified in updatedUser.

Deleting Data

// Introduction: Deleting a user with a specific username from the 'users' table.
pool.query(
  "DELETE FROM users WHERE username = ?",
  ["john_doe"],
  (err, results) => {
    if (err) {
      console.error("Error deleting data:", err)
      return
    }

    // 'results' may contain information about the deleted row
    console.log("Data deleted successfully!")
  }
)

Upon executing the DELETE query, the user with the username ‘john_doe’ will be removed from the ‘users’ table in the database.

Handling Errors

In any production application, it’s vital to handle errors gracefully to ensure your application remains robust and resilient in the face of unexpected database issues.

Conclusion

MariaDB is a powerful RDBMS that seamlessly integrates with JavaScript and Node.js applications. In this comprehensive guide, we covered the basics of setting up a MariaDB connection and performing common database operations. As you gain more experience with MariaDB, you can explore its advanced features and optimizations to build efficient and reliable database-driven applications. With these skills, you’ll be well-equipped to develop robust data-centric applications using JavaScript and Node.js with MariaDB as your database backend.