ubuntu

ubuntu里nodejs如何连接数据库

小樊
40
2025-04-01 08:29:39
栏目: 编程语言

在Ubuntu系统中,Node.js可以通过各种数据库驱动程序连接到数据库。以下是一些常见数据库的连接方法:

  1. 连接到MongoDB:

首先,安装MongoDB驱动程序:

npm install mongodb

然后,使用以下代码连接到MongoDB数据库:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://username:password@localhost:27017/myDatabase";

MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
  if (err) throw err;
  const db = client.db("myDatabase");
  // 在这里执行数据库操作
  client.close();
});
  1. 连接到MySQL:

首先,安装MySQL驱动程序:

npm install mysql

然后,使用以下代码连接到MySQL数据库:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'myDatabase'
});

connection.connect(err => {
  if (err) throw err;
  console.log('Connected to the database!');
  // 在这里执行数据库操作
});
  1. 连接到PostgreSQL:

首先,安装PostgreSQL驱动程序:

npm install pg

然后,使用以下代码连接到PostgreSQL数据库:

const { Client } = require('pg');
const client = new Client({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'myDatabase'
});

client.connect(err => {
  if (err) throw err;
  console.log('Connected to the database!');
  // 在这里执行数据库操作
});

请根据您使用的数据库类型选择相应的驱动程序,并确保将示例代码中的usernamepasswordmyDatabase替换为您的实际数据库凭据和名称。

0
看了该问题的人还看了