ubuntu

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

小樊
38
2025-11-08 13:33:03
栏目: 编程语言

要在Node.js中连接到Ubuntu上的数据库,首先需要确保已经在Ubuntu上安装了所需的数据库(例如MySQL、PostgreSQL等)。以下是使用Node.js连接到Ubuntu上的MySQL和PostgreSQL数据库的示例。

连接到MySQL数据库:

  1. 在Ubuntu上安装MySQL服务器:
sudo apt update
sudo apt install mysql-server
  1. 安装Node.js MySQL驱动程序:
npm install mysql
  1. 创建一个名为connect-mysql.js的文件,并添加以下代码:
const mysql = require('mysql');

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

connection.connect(error => {
  if (error) throw error;
  console.log('Successfully connected to the MySQL database.');
});

connection.end();
  1. 替换your_usernameyour_passwordyour_database为您的MySQL数据库凭据,然后运行脚本:
node connect-mysql.js

连接到PostgreSQL数据库:

  1. 在Ubuntu上安装PostgreSQL服务器:
sudo apt update
sudo apt install postgresql postgresql-contrib
  1. 安装Node.js PostgreSQL驱动程序:
npm install pg
  1. 创建一个名为connect-postgres.js的文件,并添加以下代码:
const { Client } = require('pg');

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

client.connect(error => {
  if (error) throw error;
  console.log('Successfully connected to the PostgreSQL database.');
});

client.end();
  1. 替换your_usernameyour_passwordyour_database为您的PostgreSQL数据库凭据,然后运行脚本:
node connect-postgres.js

这些示例将帮助您在Node.js中连接到Ubuntu上的MySQL和PostgreSQL数据库。如果您使用的是其他数据库,请查找相应的Node.js驱动程序并按照类似的步骤进行操作。

0
看了该问题的人还看了