The Wayback Machine - https://web.archive.org/web/20240603001422/https://www.geeksforgeeks.org/how-to-import-data-from-csv-file-into-mysql-table-using-node-js/
Open In App

How to import data from .CSV file into MySQL table using Node.js ?

Last Updated : 19 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

What is .CSV file?
The .CSV (Comma Separated Values) files are plain text files that contains a list of data separated by comma(,). It is a format best used for tabular data, row, and columns, exactly like a spreadsheet, just the difference is that the file is in the form of plain text. The idea of a CSV file is to perform export and import complex data from one application to another.

Note: Here, we are using sample.csv to demonstrate our program and procedure. In sample.csv we have stored the user’s Name, Age, Email, and City.

Data in sample.csv

Import CSV into MySQL using Node.js:

  1. Create a node.js project using “npm init” and save your .csv file in the same directory. 
  2. Install two packages “mysql” and “csvtojson” using the following command:
    npm i mysql csvtojson

    mysql driver: This is a node.js driver for mysql. It is written in JavaScript, that does not require compiling. We are using it to establish connection with our MYSQL database and perform queries.
    csvtojson: Its a csv parser to convert csv to json or column arrays.

  3. Now just create a file like index.js and write down the following code:




// Importing mysql and csvtojson packages
// Requiring module
const csvtojson = require('csvtojson');
const mysql = require("mysql");
  
// Database credentials
const hostname = "localhost",
    username = "root",
    password = "root",
    databsename = "csvtomysql"
  
  
// Establish connection to the database
let con = mysql.createConnection({
    host: hostname,
    user: username,
    password: password,
    database: databsename,
});
  
con.connect((err) => {
    if (err) return console.error(
            'error: ' + err.message);
  
    con.query("DROP TABLE sample", 
        (err, drop) => {
  
        // Query to create table "sample"
        var createStatament = 
        "CREATE TABLE sample(Name char(50), " +
        "Email char(50), Age int, city char(30))"
  
        // Creating table "sample"
        con.query(createStatament, (err, drop) => {
            if (err)
                console.log("ERROR: ", err);
        });
    });
});
  
// CSV file name
const fileName = "sample.csv";
  
csvtojson().fromFile(fileName).then(source => {
  
    // Fetching the data from each row 
    // and inserting to the table "sample"
    for (var i = 0; i < source.length; i++) {
        var Name = source[i]["Name"],
            Email = source[i]["Email"],
            Age = source[i]["Age"],
            City = source[i]["City"]
  
        var insertStatement = 
        `INSERT INTO sample values(?, ?, ?, ?)`;
        var items = [Name, Email, Age, City];
  
        // Inserting data of current row
        // into database
        con.query(insertStatement, items, 
            (err, results, fields) => {
            if (err) {
                console.log(
    "Unable to insert item at row ", i + 1);
                return console.log(err);
            }
        });
    }
    console.log(
"All items stored into database successfully");
});


Run index.js file using the following command:

node index.js

Output:

Output of the program in console

Sample table in MYSQL database

Explanation of code:

  • At the first two lines of code we Import  mysql and csvtojson.
    const csvtojson = require('csvtojson');
    const mysql = require("mysql")
  • Line 10 – 23 : We created a connection to our database.
    hostname = "localhost", 
    username = "root",         // Username of Mysql local server 
    password = "root",         // Password of Mysql local server
    databsename = "csvtomysql" // Database we are connecting to
  • Line 23 – 38: We have connected to our database “csvtomysql” and created table named “sample” with desired fields according to our sample.csv file.
  • Line 42 – 64 : We fetched sample.csv located in current directory and converted all the data to JSON.
    • At line 43 all data in sample.csv is converted to JSON and stored in variable “source”
    • Then we loop through each each row and extracted Name, Email, Age and City value from that row. 
      • At line 53, we created a array of values in Name, Email, Age and City i.e. the column data of ith row.
      • Then we inserted that data into table using  query “INSERT INTO sample values(Name, Email, Age, City)”
      • At line 62 we are showing the inserted data to console. 

So, this way we can import any data from a .csv file to our MYSQL database.



Similar Reads

Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
Load CSV Data into MySQL Server Using PHP
In this article, we are going to store data present in CSV file into MySQL database using PHP in XAMPP server and display the data on web browser. Comma Separated Value (CSV) is a text file containing data contents. It facilitates the storage of data in a table like structure. CSV files are stored with a CSV extension. A CSV file can be created wit
3 min read
Less.js @import At-Rules Import Options
LESS is a Leaner Style Sheets, a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets comp
3 min read
Node.js MySQL Insert into Table
NodeJs: An open-source platform for executing javascript code on the server side. Also, a javascript runtime built on Chrome’s V8 JavaScript engine. It can be downloaded from here. Mysql An open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is the most popular language for adding, accessing, and
3 min read
How to import regular CSS file in SCSS file ?
In this article, we will learn how to import regular CSS files into SCSS files. Syntactically Awesome Style Sheet is the superset of CSS. SCSS is the more advanced version of CSS. SCSS was designed by Hampton Catlin and was developed by Chris Eppstein and Natalie Weizenbaum. Due to its advanced features, it is often termed Sassy CSS. SCSS have file
3 min read
How to import all exports of a file as an object in Node.js ?
The import keyword is used in Javascript to use the elements that are exported from other modules. The syntax for importing all exports of a file as an object is as follows. Syntax: import * as objName from "abc-module" ... let element1 = objName.value1 Here, objName is any name you give while first initializing the object when you import everythin
2 min read
How to Convert JSON file into CSV in PHP ?
In this article, we are going to see how to convert JSON data into a CSV file using PHP. JSON (JavaScript Object Notation) is a dictionary-like notation that can be used to structuring data. It is stored with the extension .json, for example - geeksforgeeks.json On the other hand, CSV (or Comma Separated Value) files represent data in a tabular for
2 min read
How to Display Data from CSV file using PHP ?
We have given the data in CSV file format and the task is to display the CSV file data into the web browser using PHP. To display the data from CSV file to web browser, we will use fgetcsv() function. Comma Separated Value (CSV) is a text file containing data contents. It is a comma-separated value file with .csv extension, which allows data to be
2 min read
How to Export data to CSV file from Database using XAMPP ?
In this article, we are going to load the data present in the database (MySQL) into CSV file. Display the data in the database and also export that data into CSV file. We are using XAMPP tool to store locally in a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website d
3 min read
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
A CSV is a comma-separated value file, identified by the .csv extension, is a format used for tabular data storage where values are separated by commas. This article presents a method to convert CSV data to JavaScript Object Notation (JSON) without any relaying on third-party npm packages. Unlike typical conversions, this approach handles scenarios
4 min read