How to use MySQL in Node.js

Introduction

MySQL is a popular open-source relational database management system (RDBMS) that uses Structured Query Language (SQL) for managing and manipulating data. It is one of the most widely used databases in the world, with applications ranging from small-scale web applications to large-scale enterprise systems.

MySQL was first released in 1995 by MySQL AB (later acquired by Sun Microsystems and then by Oracle Corporation). It is written in C and C++, and it supports a wide range of operating systems, including Windows, Linux, and macOS.

MySQL offers a range of features, including support for multiple storage engines, transactions, stored procedures, triggers, views, and more. It also supports replication, clustering, and sharding for scaling and high availability.

MySQL is used by many popular websites and applications, including Facebook, Twitter, LinkedIn, and YouTube. It is also a popular choice for developers working with Node.js, PHP, and other programming languages, thanks to its ease of use, flexibility, and performance.

To use MySQL in Node.js, you need to follow these steps:

Step 1: Install the mysql package

npm install mysql

Step 2: Create a connection to the MySQL database

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'mydatabase'
});

connection.connect((error) => {
  if (error) {
    console.error('Error connecting to MySQL:', error);
  } else {
    console.log('Connected to MySQL database');
  }
});

In this example, we create a connection object using the createConnection() method and pass the connection parameters such as host, user, password, and database.

Step 3: Perform database operations
Once you have connected to the MySQL database, you can perform various database operations such as inserting, updating, deleting, and selecting data. Here are some examples:

Insert data:

const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';
const values = ['John Doe', 'john.doe@example.com'];

connection.query(sql, values, (error, result) => {
  if (error) {
    console.error('Error inserting data:', error);
  } else {
    console.log(`Inserted ${result.affectedRows} row(s)`);
  }
});

Update data:

const sql = 'UPDATE users SET name = ? WHERE id = ?';
const values = ['Jane Doe', 1];

connection.query(sql, values, (error, result) => {
  if (error) {
    console.error('Error updating data:', error);
  } else {
    console.log(`Updated ${result.affectedRows} row(s)`);
  }
});

Delete data:

const sql = 'DELETE FROM users WHERE id = ?';
const values = [1];

connection.query(sql, values, (error, result) => {
  if (error) {
    console.error('Error deleting data:', error);
  } else {
    console.log(`Deleted ${result.affectedRows} row(s)`);
  }
});

Select data:

const sql = 'SELECT * FROM users';

connection.query(sql, (error, results) => {
  if (error) {
    console.error('Error selecting data:', error);
  } else {
    console.log(`Selected ${results.length} row(s)`);
    console.log('Data:', results);
  }
});

In this example, we use the query() method to perform SQL queries. The first argument is the SQL query, and the second argument (if present) is an array of values to substitute in the SQL query. The third argument is a callback function that gets called when the query is executed. If there is an error, the error object is passed to the callback function, and if the query is successful, the result object is passed to the callback function.

, , ,

Related posts

Latest posts

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Please disable your adblocker or whitelist this site!

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site