Home >>Nodejs Tutorial >Node.js MySQL Create Table

Node.js MySQL Create Table

Node.js MySQL Create Table

The command Build TABLE is used to build a table in MySQL. When making the connection, you have to make sure that you define the database name.

Example For creating a table named "users".

Build a javascript file called users.js that has the following data in the folder example.


var tab = require('tab');  
var con = tab.createConnection({  
host: "localhost",  
user: "root",  
password: "",  
database: "phptpoint"  
});  
con.connect(function(err) {  
if (err) throw err;  
console.log("Connected!");  
var sql = "CREATE TABLE users (id INT, name VARCHAR(255), email VARCHAR(255))";  
con.query(sql, function (err, result) 
{  
if (err) throw err;  
console.log("Table created");  
});  
});  

Now open terminal command and execute the following command:

Node users.js

Verification

Using the SHOW TABLES command to check whether a table is built or not.


Create Table Having a Primary Key

Create Primary Key in New Table:

Let's build a new table called "users2" which has id as its primary key.

Creates a javascript file called users2.js with the following data in the folder DBexample.


var db = require('db');  
var con = db.createConnection({  
host: "localhost",  
user: "root",  
password:"",  
database: ""  
});  
con.connect(function(err) {  
if (err) throw err;  
console.log("Connected!");  
var sql = "CREATE TABLE users2 (id INT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))";  
con.query(sql, function (err, result) 
{  
if (err) throw err;  
console.log("Table created");  
});  
}); 

Now open terminal command and execute the following command:

Node users2.js

Verification

Using the SHOW TABLES command to check whether a table is built or not.

You may also use DESC command to test the table structure to see that id is the primary key:

Add columns in existing Table:

The statement ALTER TABLE is used to add a section to an existing table. Take the "users2" table already created, and use a new salary column.

Replace the table "users2" data by the following data:


var db = require('db');  
var con = db.createConnection({  
host: "localhost",  
user: "root",  
password: "",  
database: "phptpoint"  
});  
con.connect(function(err) {  
if (err) throw err;  
console.log("Connected!");  
var sql = "ALTER TABLE users2 ADD COLUMN salary INT(10)";  
con.query(sql, function (err, result) 
{  
if (err) throw err;  
console.log("Table altered");  
});  
});  

Now open terminal command and execute the following command:

Node users2.js

Verification

In table user2 a new column salary is created.