Node.js - MySQL TRUNCATE
In this post, we will discuss how to delete all the rows from MySQL XAMPP Server using Node.js with TRUNCATE Command.
It is important to install mysql package in node.js
Command to install the mysql package:
Copied
npm install mysql
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 uses TRUNCATE command
- 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 delete_query = "TRUNCATE TABLE table_name";
connection_data.query(delete_query, function (error, result) {
console.log("All rows deleted Successfully!");
});
});
Consider the field table with the following records:
TRUNCATE Example:-
Let's delete all rows from field.
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) {
// Delete all records in field table.
var delete_query = "TRUNCATE TABLE field";
connection_data.query(delete_query, function (error, result) {
console.log("All rows deleted Successfully!");
});
});
Output:
Copied
All rows deleted Successfully!
Let's check in our XAMPP Server whether all the rows deleted or not.
SummaryIn this post, we seen how to delete all the rows from mysql table with TRUNCATE Command using Node.js script in XAMPP Server.