In this tutorial you will learn about the Nodejs MySql Create Table and its application with practical example.
Node.js MySql Create Table
MySQL Database Table can simply be created using “CREATE TABLE” statement.
Example :- Let’s create MySQL database Table named as “employees” under “nodemysql” database.
Step 1:- Let’s, create a node_mysql_create_tbl.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "nodemysql" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); var sql = "CREATE TABLE employees (id INT PRIMARY KEY, emp_name VARCHAR(255), emp_age INT(3))"; con.query(sql, function (err, result) { if (err) throw err; console.log("W3Adda | MySQL Employees Table created"); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mysql_create_tbl.js |
you will see following output on terminal –
![Node.js MySql Create Table 1](http://w3adda.com/wp-content/uploads/2018/04/1-3.jpg)
Node.js MySql Create Table 1
![Node.js MySql Create Table 2](http://w3adda.com/wp-content/uploads/2018/04/2-3.jpg)
Node.js MySql Create Table 2
Add Columns to existing Table
A column can easily be added to an existing MySQL Table using the “ALTER TABLE” statement.
Example :- Let’s add “emp_salary” to database Table “employees”.
Step 1:- Let’s, create a node_mysql_alter_tbl.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "nodemysql" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); var sql = "ALTER TABLE employees ADD COLUMN emp_salary INT(10)"; con.query(sql, function (err, result) { if (err) throw err; console.log("W3Adda | MySQL Table altered"); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mysql_alter_tbl.js |
you will see following output on terminal –
![Node.js MySql Alter Table 1](http://w3adda.com/wp-content/uploads/2018/04/alter-1.jpg)
Node.js MySql Alter Table 1
![Node.js MySql Alter Table 2](http://w3adda.com/wp-content/uploads/2018/04/alter-2.jpg)
Node.js MySql Alter Table 2