How to connect nodejs to database

下次还敢
Release: 2024-04-21 05:07:11
Original
693 people have browsed it

Steps to connect to a database in Node.js: Install the MySQL, MongoDB or PostgreSQL package. Create a database connection object. Open a database connection and handle connection errors.

How to connect nodejs to database

How to connect to the database in Node.js

Connect to the MySQL database

To connect to a MySQL database, you can use the following steps:

  1. InstallmysqlPackage:npm install mysql
  2. Create a database Connection object:
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'username', password: 'password', database: 'database_name' });
Copy after login
  1. Open database connection:
connection.connect((err) => { if (err) { console.log('Error connecting to database:', err); return; } console.log('Connected to MySQL database'); });
Copy after login

Connect to MongoDB database

To connect to MongoDB database, You can use the following steps:

  1. InstallmongodbPackage:npm install mongodb
  2. Create a database connection object:
const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017';
Copy after login
  1. Open database connection:
MongoClient.connect(url, (err, client) => { if (err) { console.log('Error connecting to database:', err); return; } console.log('Connected to MongoDB database'); // 使用 client 对象进行数据库操作 });
Copy after login

Connect to PostgreSQL database

To connect to PostgreSQL database, you can use the following steps:

  1. InstallpgPackage:npm install pg
  2. Create a database connection object:
const pg = require('pg'); const connectionString = 'postgres://username:password@localhost:5432/database_name'; const client = new pg.Client(connectionString);
Copy after login
  1. Open database connection:
client.connect((err) => { if (err) { console.log('Error connecting to database:', err); return; } console.log('Connected to PostgreSQL database'); });
Copy after login

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

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!