How to use MySQL database with Node.js?

27 January 2023 402 Reading time: 1 minute

We can use "mysql" package to connect to MySQL database with Node.js. For this, first we need to install the mysql package using the 'npm i mysql' command.
Afterwards, you can connect to the database as in the code block below and use SELECT, INSERT, UPDATE and DELETE queries.

const mysql = require('mysql');

// Creating the database connection
const con = mysql.createConnection({
  host: "localhost",
  user: "username",
  password: "password",
  database: "database_name"
});

// Connecting to the database
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected to database!");

  // SELECT query
  con.query("SELECT * FROM tablo_adi", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });

  // INSERT query
  var sql = "INSERT INTO tablo_adi (colomn1, colomn2) VALUES ('val1', 'val2')";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("1 record added");
  });

  // UPDATE query
  var sql = "UPDATE table_name SET colmn1 = 'val1' WHERE id = 2";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result.affectedRows + " record updated");
  });

  // DELETE query
  var sql = "DELETE FROM table_name WHERE id = 3";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result.affectedRows + " record deleted");
  });
});

Similar articles