Skip to main content

One post tagged with "query"

View All Tags

ยท 2 min read
Kumar Nitesh

Beginner guide to connect to MySQL with NodeJS

Start a Node JS project

> mkdir nodejs-mysql> cd nodejs-mysql> npm init -y

install mysql package

> npm i --save mysql

create a server.js file

> touch server.js

Open nodejs-mysql in your favorite editor and add following code to server.js

const mysql = require('mysql')
// create connection object for DB, you can get all below values from the connection stringconst connectionConfig = {    host: '<replace_with_your_db_server>', // if mysql is running locally it may be 'localhost'    user: '<replace_with_user_id_having_access_to_your_db>',    password: '<replace_with_db_password>',    database: '<default_database_to_connect>'}// initialize with connection configconst db = mysql.createConnection(connectionConfig)
// connect to the serverdb.connect(function(err){    if(err) throw err    console.log("MySQL DB connected successfully!")})
// create query for your dbconst sql =`select * from dbName.tableName`;
// query your db    db.query(sql, function(err,result){        if(err) throw err        console.log(result)        Object.keys(result).forEach((key)=>{            console.log(result[key])            })    })

    // don't forget to close your connection    db.end(err=>{        if(err) throw err        console.log('Connection to MySQL is successfully closed')    })}

To run code, run below command in terminal

> node server.js

You should see the result of your query in the terminal. To save query result in a file you can use csv-stringify package. Here is small code snippet for the same

...const fs = require('fs');const stringify = require('csv-stringify');......
// queryResult is a string value filtered after querying databasestringify(queryResult, function(err, output) {            fs.writeFile('query.csv', output, 'utf8', function(err) {              if (err) {                console.log('Some error occured - file either not saved or corrupted file saved.');              } else {                console.log('It\'s saved!');              }            });        });