Creating MySQL Databases Programmatically with Node.js: A Step-by-Step Guide

Learn how to create new MySQL databases using Node.js and the MySQL connector library. This tutorial provides a clear, step-by-step process with code examples, demonstrating how to connect to your MySQL server, execute the `CREATE DATABASE` statement, and verify the creation of your new database.



Creating a MySQL Database Using Node.js

This tutorial demonstrates how to create a new database in MySQL using Node.js and the MySQL connector library. Creating a database is a fundamental task in database management.

Understanding the `CREATE DATABASE` Statement

In MySQL, the `CREATE DATABASE` statement creates a new, empty database. This is the first step in setting up a database to store your application's data. The database name should be chosen carefully, and you will need appropriate privileges to create new databases.

Creating a Database Using Node.js

This example shows how to create a database named "tutorialsarena" using Node.js and the MySQL connector. (Remember to replace `"root"` and `"12345"` with your actual MySQL username and password.)


const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'your_password' // Replace with your MySQL password
});

connection.connect(err => {
  if (err) throw err;
  console.log('Connected!');
  connection.query('CREATE DATABASE IF NOT EXISTS mydatabase', (err, result) => {
    if (err) throw err;
    console.log('Database created!');
  });
  connection.end();
});

This code connects to the MySQL server, executes the `CREATE DATABASE` statement, and then prints a success message. The `IF NOT EXISTS` clause prevents errors if the database already exists. The connection is closed using `connection.end()` after the database creation.

Verifying Database Creation

After running the Node.js script, you can verify that the database was created using the MySQL command-line client (`mysql`). Connect to the MySQL server and use the `SHOW DATABASES;` command to list all available databases. Your newly created database should be in this list.

(The original text mentions using `mysql-p` to specify a password; please refer to the original document for details on using the MySQL command-line client.)