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
Copy after login

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!');
});
Copy after login

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);
});
Copy after login

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!');
});
Copy after login

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React and the Frontend: Building Interactive Experiences React and the Frontend: Building Interactive Experiences Apr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React Components: Creating Reusable Elements in HTML React Components: Creating Reusable Elements in HTML Apr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React's Ecosystem: Libraries, Tools, and Best Practices React's Ecosystem: Libraries, Tools, and Best Practices Apr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

Frontend Development with React: Advantages and Techniques Frontend Development with React: Advantages and Techniques Apr 17, 2025 am 12:25 AM

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React: The Power of a JavaScript Library for Web Development React: The Power of a JavaScript Library for Web Development Apr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React vs. Backend Frameworks: A Comparison React vs. Backend Frameworks: A Comparison Apr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

The Future of React: Trends and Innovations in Web Development The Future of React: Trends and Innovations in Web Development Apr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

See all articles