Table of Contents
Install Node.js and MySQL database
Install the mysql module
Connecting to a MySQL database
Execute SQL Query
Insert, update or delete data
Summary
Home Web Front-end Front-end Q&A How to operate mysql with nodejs

How to operate mysql with nodejs

May 28, 2023 am 09:02 AM

Node.js is a very powerful JavaScript runtime environment that can be used to develop various types of applications, including web applications, command line tools, and various back-end services. Its power lies in its rich modular ecosystem, which includes many modules for database connection and management. Among them, the mysql module is used to connect to the MySQL database.

In this article, we will introduce how to use Node.js to connect and manage MySQL database. The steps are roughly as follows:

  1. Install Node.js and MySQL database.
  2. Install the mysql module.
  3. Connect to MySQL database.
  4. Execute SQL query.
  5. Insert, update or delete data.

Next, we will introduce it step by step.

Install Node.js and MySQL database

First, you need to make sure that Node.js and MySQL database are installed on your computer. If you have not installed these two software, you can visit the following link to download:

  • Node.js: https://nodejs.org/
  • MySQL: https://www .mysql.com/downloads/

Node.js installation is very simple. Just download the installation package of the corresponding version and follow the prompts to install it.

The installation of MySQL is also very simple. You just need to follow the prompts to download and install. When the installation is complete, you will need to set a root password. This password will be used to authenticate you when connecting to the MySQL database in Node.js. In this article, we assume that the root password is yourPassword.

Install the mysql module

Once you have installed Node.js, you can use npm (Node.js package manager) to install the mysql module. Open a terminal (or command line) and run the following command:

npm install mysql

This command will install the mysql module and add it to your project dependencies.

Connecting to a MySQL database

Next, we need to create a MySQL database and write code in Node.js to connect to the database. We will use the following code in Node.js to connect to the database:

const mysql = require('mysql');

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

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected!');
});

In this code, we first import the mysql module. Next, we use the createConnection() method to create a connection object that contains some information needed to connect to the database, such as hostname, username, password, and database name. Here, we use localhost as the hostname, root as the username, yourPassword as the password, and mydatabase as the database name.

Once we have established the connection object, we will use the connect() method to connect to the database. This method will issue a connection request and wait for a response. If the request is successful, a "Connected!" message is printed; otherwise, an error is thrown and an error message is printed.

Execute SQL Query

Now, we have successfully connected to the MySQL database. We will use the mysql module in Node.js to execute SQL queries. First, we'll cover how to execute a SELECT query. The following is a sample code:

connection.query('SELECT * FROM users', (err, results) => {
  if (err) throw err;
  console.log(results);
});

In this code, we use the query() method of the connection object to perform a SELECT query. This method accepts two parameters: the SQL query to be executed and a callback function. When the query is complete, the callback function will be called and the query results will be returned as the second parameter. If an error occurs, an error is thrown and an error message is printed.

Insert, update or delete data

In addition to querying data, we can also use Node.js and the mysql module to insert, update or delete data. The following is a sample code:

// 插入数据
const user = { name: 'John', email: 'john@example.com' };
connection.query('INSERT INTO users SET ?', user, (err, results) => {
  if (err) throw err;
  console.log('Inserted!');
});

// 更新数据
const newEmail = 'newEmail@example.com';
connection.query('UPDATE users SET email = ? WHERE name = ?', [newEmail, 'John'], (err, results) => {
  if (err) throw err;
  console.log('Updated!');
});

// 删除数据
connection.query('DELETE FROM users WHERE name = ?', 'John', (err, results) => {
  if (err) throw err;
  console.log('Deleted!');
});

In this code, we first define an object named user that contains the data we want to insert. We use INSERT INTO statement to insert data. Here we use SET clause to set the data. When the insertion is successful, we print the "Inserted!" message.

We use the UPDATE statement to update data. Here, we use the WHERE clause to specify the rows to be updated. When the update is successful, we will print the "Updated!" message.

Finally, we use the DELETE statement to delete data. Here we use WHERE clause to specify the rows to be deleted. When the deletion is successful, we will print the "Deleted!" message.

Summary

In this article, we introduced how to use Node.js and the mysql module to connect and manage a MySQL database. We discussed how to install Node.js and a MySQL database and connect to the database using the mysql module. We also demonstrated how to perform SQL queries and insert, update, or delete data.

The sample code in this article will be useful if you are developing a Node.js application and need to connect to a MySQL database. Don’t forget to refer to the official documentation and community resources for more information and guidance on Node.js and the mysql module.

The above is the detailed content of How to operate mysql with nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are ARIA attributes What are ARIA attributes Jul 02, 2025 am 01:03 AM

ARIAattributesenhancewebaccessibilityforuserswithdisabilitiesbyprovidingadditionalsemanticinformationtoassistivetechnologies.TheyareneededbecausemodernJavaScript-heavycomponentsoftenlackthebuilt-inaccessibilityfeaturesofnativeHTMLelements,andARIAfill

How does React handle focus management and accessibility? How does React handle focus management and accessibility? Jul 08, 2025 am 02:34 AM

React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementation; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.

How to minimize HTTP requests How to minimize HTTP requests Jul 02, 2025 am 01:18 AM

Let’s talk about the key points directly: Merging resources, reducing dependencies, and utilizing caches are the core methods to reduce HTTP requests. 1. Merge CSS and JavaScript files, merge files in the production environment through building tools, and retain the development modular structure; 2. Use picture Sprite or inline Base64 pictures to reduce the number of image requests, which is suitable for static small icons; 3. Set browser caching strategy, and accelerate resource loading with CDN to speed up resource loading, improve access speed and disperse server pressure; 4. Delay loading non-critical resources, such as using loading="lazy" or asynchronous loading scripts, reduce initial requests, and be careful not to affect user experience. These methods can significantly optimize web page loading performance, especially on mobile or poor network

Describe the difference between shallow and full rendering in React testing. Describe the difference between shallow and full rendering in React testing. Jul 06, 2025 am 02:32 AM

Shallowrenderingtestsacomponentinisolation,withoutchildren,whilefullrenderingincludesallchildcomponents.Shallowrenderingisgoodfortestingacomponent’sownlogicandmarkup,offeringfasterexecutionandisolationfromchildbehavior,butlacksfulllifecycleandDOMinte

What is the significance of the StrictMode component in React? What is the significance of the StrictMode component in React? Jul 06, 2025 am 02:33 AM

StrictMode does not render any visual content in React, but it is very useful during development. Its main function is to help developers identify potential problems, especially those that may cause bugs or unexpected behavior in complex applications. Specifically, it flags unsafe lifecycle methods, recognizes side effects in render functions, and warns about the use of old string refAPI. In addition, it can expose these side effects by intentionally repeating calls to certain functions, thereby prompting developers to move related operations to appropriate locations, such as the useEffect hook. At the same time, it encourages the use of newer ref methods such as useRef or callback ref instead of string ref. To use Stri effectively

Vue with TypeScript Integration Guide Vue with TypeScript Integration Guide Jul 05, 2025 am 02:29 AM

Create TypeScript-enabled projects using VueCLI or Vite, which can be quickly initialized through interactive selection features or using templates. Use tags in components to implement type inference with defineComponent, and it is recommended to explicitly declare props and emits types, and use interface or type to define complex structures. It is recommended to explicitly label types when using ref and reactive in setup functions to improve code maintainability and collaboration efficiency.

How to handle forms in Vue How to handle forms in Vue Jul 04, 2025 am 03:10 AM

There are three key points to be mastered when processing Vue forms: 1. Use v-model to achieve two-way binding and synchronize form data; 2. Implement verification logic to ensure input compliance; 3. Control the submission behavior and process requests and status feedback. In Vue, form elements such as input boxes, check boxes, etc. can be bound to data attributes through v-model, such as automatically synchronizing user input; for multiple selection scenarios of check boxes, the binding field should be initialized into an array to correctly store multiple selected values. Form verification can be implemented through custom functions or third-party libraries. Common practices include checking whether the field is empty, using a regular verification format, and displaying prompt information when errors are wrong; for example, writing a validateForm method to return the error message object of each field. You should use it when submitting

Server-Side Rendering with Next.js Explained Server-Side Rendering with Next.js Explained Jul 23, 2025 am 01:39 AM

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS

See all articles