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 to the database in Node.js
Connect to the MySQL database
To connect to a MySQL database, you can use the following steps:
mysql
Package:npm install mysql
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'username', password: 'password', database: 'database_name' });
connection.connect((err) => { if (err) { console.log('Error connecting to database:', err); return; } console.log('Connected to MySQL database'); });
Connect to MongoDB database
To connect to MongoDB database, You can use the following steps:
mongodb
Package:npm install mongodb
const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const url = 'mongodb://localhost:27017';
MongoClient.connect(url, (err, client) => { if (err) { console.log('Error connecting to database:', err); return; } console.log('Connected to MongoDB database'); // 使用 client 对象进行数据库操作 });
Connect to PostgreSQL database
To connect to PostgreSQL database, you can use the following steps:
pg
Package:npm install pg
const pg = require('pg'); const connectionString = 'postgres://username:password@localhost:5432/database_name'; const client = new pg.Client(connectionString);
client.connect((err) => { if (err) { console.log('Error connecting to database:', err); return; } console.log('Connected to PostgreSQL database'); });
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!