温馨提示×

Ubuntu上Node.js如何与数据库连接

小樊
43
2025-12-18 03:15:06
栏目: 编程语言

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

  1. MongoDB:

首先,安装MongoDB驱动程序:

npm install mongodb

然后,创建一个名为app.js的文件,并添加以下代码以连接到MongoDB数据库:

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

MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
  if (err) throw err;
  const db = client.db("myDatabase");
  console.log("Connected to MongoDB!");
  client.close();
});

最后,运行app.js文件:

node app.js
  1. MySQL:

首先,安装MySQL驱动程序:

npm install mysql

然后,创建一个名为app.js的文件,并添加以下代码以连接到MySQL数据库:

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

connection.connect(err => {
  if (err) throw err;
  console.log('Connected to MySQL database!');
});

connection.end();

最后,运行app.js文件:

node app.js
  1. PostgreSQL:

首先,安装PostgreSQL驱动程序:

npm install pg

然后,创建一个名为app.js的文件,并添加以下代码以连接到PostgreSQL数据库:

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

client.connect(err => {
  if (err) throw err;
  console.log('Connected to PostgreSQL database!');
});

client.end();

最后,运行app.js文件:

node app.js

请根据您使用的数据库和需求替换相应的配置信息。

0