Creating MySQL Tables with Node.js: A Practical Guide

Learn how to programmatically create tables in MySQL using Node.js. This tutorial provides clear code examples demonstrating the `CREATE TABLE` statement, including specifying data types, primary keys, and other table constraints, and shows how to verify table creation.



Node.js MySQL Create Table

This section demonstrates how to create tables in MySQL using Node.js. The CREATE TABLE statement is used to define new tables in your database. Make sure you have a database connection established before running these examples.

Creating a Simple Table

Let's create a table named "employees". Create a file named employees.js with the following code:

Creating "employees" Table

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "12345", // Replace with your password
    database: "tutorialsarena" // Replace with your database name
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "CREATE TABLE employees (id INT, name VARCHAR(255), age INT(3), city VARCHAR(255))";
    con.query(sql, function (err, result) {
        if (err) throw err;
        console.log("Table created");
    });
});
            

Run this script using node employees.js. Verify the table's creation using SHOW TABLES; and DESC employees; in your MySQL client.

Creating a Table with a Primary Key

Let's create a table named "employee2" with an id column as the primary key. Create a file named employee2.js:

Creating "employee2" Table with Primary Key

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "12345", // Replace with your password
    database: "tutorialsarena" // Replace with your database name
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "CREATE TABLE employee2 (id INT PRIMARY KEY, name VARCHAR(255), age INT(3), city VARCHAR(255))";
    con.query(sql, function (err, result) {
        if (err) throw err;
        console.log("Table created");
    });
});
            

Run this using node employee2.js. Verify with SHOW TABLES; and DESC employee2;.

Adding Columns to an Existing Table

The ALTER TABLE statement adds columns to existing tables. Let's add a "salary" column to the "employee2" table. Update your employee2.js file:

Adding a Column to "employee2"

var mysql = require('mysql');
// ... (connection details as above) ...

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "ALTER TABLE employee2 ADD COLUMN salary INT(10)";
    con.query(sql, function (err, result) {
        if (err) throw err;
        console.log("Table altered");
    });
});
            

Run this using node employee2.js. Verify the change using DESC employee2;.

next →

← prev