Home >Web Front-end >Front-end Q&A >How nodejs implements database
Connecting to a database in Node.js requires choosing a database system (relational or non-relational) and then establishing a connection using a module specific to that type. Common modules include mysql (MySQL), pg (PostgreSQL), mongodb (MongoDB), and redis (Redis). After the connection is established, you can use query statements to retrieve data and update statements to modify the data. Finally, the connection must be closed when all operations are completed to release resources. Improve performance and security by following these best practices, such as using connection pooling, parameterized queries, and handling errors gracefully.
How to connect and use a database in Node.js
Node.js is a popular JavaScript runtime A real-time environment typically used for building web applications and APIs. To store and manage data, Node.js can connect to various database systems.
Choose a database system
Establishing a connection
Node.js has a variety of modules for interacting with databases. The following are common modules for each database type:
mysql
or mysql2
pg
mongodb
redis
To establish a connection, you can use the following code template:
<code class="javascript">const { createConnection } = require('mysql'); const conn = createConnection({ host: 'localhost', port: 3306, user: 'root', password: '', database: 'mydb' });</code>
Query and update data
Once the connection is established , you can query and update data in the database. The following is a code sample for the query:
<code class="javascript">conn.query('SELECT * FROM users WHERE username = ?', ['jdoe'], (err, rows) => { if (err) throw err; console.log(rows); });</code>
To update the data, you can use the following code sample:
<code class="javascript">conn.query('UPDATE users SET email = ? WHERE username = ?', ['new@email.com', 'jdoe'], (err, result) => { if (err) throw err; console.log(result.affectedRows); });</code>
Close the connection
After completing all database operations , the connection should be closed to release resources. Here's how to close a MySQL connection:
<code class="javascript">conn.end();</code>
Best Practices
The above is the detailed content of How nodejs implements database. For more information, please follow other related articles on the PHP Chinese website!