๐Ÿ“‚ Node.js โ€“ MySQL: Introduction & Setup
Estimated reading: 3 minutes 21 views

๐Ÿ› ๏ธ Node.js โ€“ MySQL Create Database / Tables โ€“ Step-by-Step with SQL & Node Integration


๐Ÿงฒ Introduction โ€“ Why Create Databases and Tables from Node.js?

With Node.js and the MySQL module, you can not only run queries but also create databases and tables dynamically. This is useful for:

  • Automating initial setup
  • Running migrations
  • Generating multi-tenant databases

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to connect to MySQL server
  • Create a new database programmatically
  • Create tables with various field types
  • Handle duplicate creation and errors

โš™๏ธ Step 1 โ€“ Connect to MySQL Server

Before you create a database, connect without selecting one:

const mysql = require('mysql');

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: ''
});

db.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL Server');
});

๐Ÿ—๏ธ Step 2 โ€“ Create a Database

db.query('CREATE DATABASE IF NOT EXISTS testdb', (err, result) => {
  if (err) throw err;
  console.log('Database created or already exists');
});

๐Ÿงช Output:

Database created or already exists

๐Ÿ”— Step 3 โ€“ Connect to the Created Database

Update your connection:

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'testdb'
});

๐Ÿงฑ Step 4 โ€“ Create a Table (Users Table Example)

const sql = `
CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`;

db.query(sql, (err, result) => {
  if (err) throw err;
  console.log('Users table created');
});

๐Ÿงช Output:

Users table created

๐Ÿ“š Add More Tables (Products Table Example)

const sql = `
CREATE TABLE IF NOT EXISTS products (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100),
  price DECIMAL(10,2),
  stock INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`;

db.query(sql, (err) => {
  if (err) throw err;
  console.log('Products table created');
});

๐Ÿ“œ SQL Data Types Quick Reference

TypeUse Case
INTWhole numbers, IDs
VARCHAR(n)Strings, emails, names
TEXTLong descriptions
DECIMAL(a,b)Prices, decimals with precision
TIMESTAMPRecord time of entry

๐Ÿงฑ Best Practices for Table Creation via Node.js

โœ… Practice๐Ÿ’ก Why Itโ€™s Important
Use IF NOT EXISTSPrevent duplicate errors
Always include PRIMARY KEYMakes data uniquely identifiable
Add DEFAULT values where usefulHandles inserts without full data
Use UNIQUE for key columnsPrevents duplicate records (like email)
Add created_at timestampTracks creation time for audit/logging

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Node.js and MySQL allow you to automate database and table creation using SQL statements. This is great for app initialization, setup scripts, and reusable deployment workflows.

๐Ÿ” Key Takeaways:

  • Use CREATE DATABASE and CREATE TABLE from within Node.js
  • Always use IF NOT EXISTS to avoid redundant errors
  • Define strong schema types and constraints

โš™๏ธ Real-world relevance:
Used in startup apps, cloud automation, CMS setup, SaaS tenant provisioning, and dev/test CI environments.


โ“FAQs โ€“ Creating MySQL Databases and Tables with Node.js


โ“ Can I create a database if it already exists?
โœ… Yes, use CREATE DATABASE IF NOT EXISTS to avoid errors.


โ“ How to run multiple table creations one after another?
โœ… Chain them or wrap them in a function call to maintain sequence.


โ“ Can I drop and recreate a table dynamically?
โœ… Yes, use DROP TABLE IF EXISTS tableName followed by CREATE TABLE.


โ“ How do I handle foreign keys in table creation?
โœ… Define constraints during CREATE TABLE, or use ALTER TABLE later.


โ“ Should I use migration tools instead of manual creation?
โœ… For larger apps, tools like Sequelize or Knex.js are better for migrations, but raw SQL via Node.js is great for setup scripts and lightweight control.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ› ๏ธ Node.js โ€“ MySQL Create Database / Tables

Or Copy Link

CONTENTS
Scroll to Top