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