search
HomeWeb Front-endFront-end Q&AHow to connect nodejs to mysql

How to connect nodejs to mysql

May 11, 2023 pm 07:35 PM

Node.js is a JavaScript runtime environment that can run JavaScript code on the server side and client side. Node.js provides powerful tools and modules that allow developers to easily interact with various databases. MySQL is a popular relational database widely used in web development. In this article, we will learn how to connect to a MySQL database using Node.js.

  1. Installing MySQL

Before you start connecting to MySQL, you need to install the MySQL server on your local system and start it. You can download and install MySQL Community Server from the official website (https://dev.mysql.com/downloads/mysql/). After the installation is complete, start the MySQL server.

  1. Install the MySQL module

Connecting Node.js to MySQL requires a module called "mysql". You can install it using npm, Node.js’s package manager. Open the command line tool and run the following command:

npm install mysql
  1. Connect to MySQL

After installing the "mysql" module, we need to introduce it in the Node.js application , and use it to connect to the MySQL database. The following is a sample code that connects to MySQL and queries all records of the "users" table:

const mysql = require('mysql');

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

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected!');
  connection.query('SELECT * FROM users', (err, rows) => {
    if (err) throw err;

    console.log('Data received from MySQL:
');
    console.log(rows);
  });
});

In this example, we create a MySQL connection object using the "mysql" module. We specified the MySQL server's hostname "localhost", username "root", password "password" and database name "mydatabase".

After calling the "connect" method on the connection object, we use the "query" method to execute the SQL query. After the query is successful, we will print the query results to the console.

  1. Querying and updating data

Querying and updating data in a MySQL database is a common task. The following is the code for some sample query and update operations:

Query data:

// 查询users表的所有记录
connection.query('SELECT * FROM users', (err, rows) => {
  if (err) throw err;

  console.log('Data received from MySQL:
');
  console.log(rows);
});

// 查询ID为1的用户
connection.query('SELECT * FROM users WHERE id = ?', [1], (err, rows) => {
  if (err) throw err;

  console.log('Data received from MySQL:
');
  console.log(rows);
});

Update data:

// 将ID为1的用户的名字改为John
connection.query('UPDATE users SET name = ? WHERE id = ?', ['John', 1], (err, result) => {
  if (err) throw err;

  console.log(`Changed ${result.changedRows} rows`);
});
  1. Error handling

Errors may occur when connecting and querying the MySQL database. To ensure the stability of the code, we need to include appropriate error handling code in the code. Here is a sample error handling code:

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

  connection.query('SELECT * FROM non_existing_table', (err, rows) => {
    if (err) {
      console.log('Error executing query:', err);
    } else {
      console.log('Data received from MySQL:
');
      console.log(rows);
    }
  });
});

In this example, we are deliberately trying to query a table that does not exist. If the query fails, we will catch the error and print the error message.

Conclusion

This is a simple guide on how to connect and operate a MySQL database in Node.js. MySQL programming with Node.js can be more efficient, but you still need to handle errors and exceptions appropriately. I hope this article can make you happily use Node.js to connect to MySQL database!

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

Statement
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
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment