Node.js - MySQL ALTER ADD Column
In this post, we will discuss how to add Column to an existing MySQL table in XAMPP Server using Node.js with ALTER Command.
Command to install the mysql package:
Copied
npm install mysql
ALTER
ALTER is used to change or modify the table structure.We will see how to add a column using alter
Steps:Now let's see steps
- First start your XAMPP Server (Both Apache and MySQL).
- Open Notepad or any text-editor and write the Node.js script
- In that script, first we have to load the mysql package using the below syntax var mysql_package = require('mysql');
- Create the connection using the server,username and password.
- Write the sql query that add a column using ALTER
- Now type the following command in your command prompt to run the script. node file_name.js
Copied
var connection_data = mysql_package.createConnection({
host: "localhost",
user: "root",
password: "",
database:"database_name"
});
Copied
connection_data.connect(function(error) {
var sql_query = "ALTER TABLE table_name
ADD column datatype;";
connection_data.query(sql_query, function (error, result) {
console.log("Column added Successfully");
});
});
Consider the village table with the following records:
Alter Column Example 1:
Let's add a new column named = column1 to the village table with int datatype.
Copied
// Load the mysql package
var mysql_package = require('mysql');
// Create the connection using the server,username and password.
//In my scenario - server is the localhost,
//username is root,
//password is empty.
//database is facility
var connection_data = mysql_package.createConnection({
host: "localhost",
user: "root",
password: "",
database:"facility"
});
connection_data.connect(function(error) {
// Query to add a column named - column1 with integer type.
var sql_query = "ALTER TABLE village ADD column1 int";
connection_data.query(sql_query, function (error, result) {
console.log("column1 added successfully");
});
});
Output:
Copied
column1 added successfully
Let's check in our XAMPP Server whether the column1 is added or not.
Alter Column Example 2:
Copied
// Load the mysql package
var mysql_package = require('mysql');
// Create the connection using the server,username and password.
//In my scenario - server is the localhost,
//username is root,
//password is empty.
//database is facility
var connection_data = mysql_package.createConnection({
host: "localhost",
user: "root",
password: "",
database:"facility"
});
connection_data.connect(function(error) {
// Query to add a column named - column1 with varchar type.
var sql_query = "ALTER TABLE village ADD column2 varchar(30)";
connection_data.query(sql_query, function (error, result) {
console.log("column2 added successfully");
});
});
Output:
Copied
column2 added successfully
Let's check in our XAMPP Server whether the column2 is added or not.
SummaryIn this post, we saw how to add a column to the MySQL table in XAMPP Server through ALTER Command with Node.js Script.