Home  >  Article  >  Web Front-end  >  How to connect nodejs to database

How to connect nodejs to database

下次还敢
下次还敢Original
2024-04-21 05:07:11733browse

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. Install mysql Package: npm install mysql
  2. Create a database Connection object:
<code class="typescript">const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});</code>
  1. Open database connection:
<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:

  1. Installmongodb Package:npm install mongodb
  2. Create a database connection object:
<code class="typescript">const mongo = require('mongodb');

const MongoClient = mongo.MongoClient;
const url = 'mongodb://localhost:27017';</code>
  1. Open database connection:
<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:

  1. Installpg Package: npm install pg
  2. Create a database connection object:
<code class="typescript">const pg = require('pg');

const connectionString = 'postgres://username:password@localhost:5432/database_name';

const client = new pg.Client(connectionString);</code>
  1. Open database connection:
<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!

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