ubuntu上nodejs如何连接数据库

在Ubuntu上使用Node.js连接数据库,首先需要确保已经安装了Node.js和相应的数据库。以下是连接MySQL和MongoDB数据库的示例。

  1. 连接MySQL数据库:

步骤1:安装MySQL服务器

sudo apt update
sudo apt install mysql-server

步骤2:安装Node.js MySQL驱动

sudo apt install nodejs npm
npm install mysql

步骤3:创建一个名为app.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 database.');
});

// Your query and other operations go here

connection.end();

步骤4:运行app.js文件

node app.js
  1. 连接MongoDB数据库:

步骤1:安装MongoDB服务器

sudo apt update
sudo apt install -y mongodb

步骤2:安装Node.js MongoDB驱动

npm install mongodb

步骤3:创建一个名为app.js的文件,并添加以下代码:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://your_username:your_password@localhost:27017/your_database";

MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
  if (err) throw err;
  console.log('Successfully connected to the database.');

  const db = client.db('your_database');
  // Your query and other operations go here

  client.close();
});

步骤4:运行app.js文件

node app.js

请根据实际情况替换your_usernameyour_passwordyour_database。这些示例适用于本地数据库连接。如果需要连接到远程数据库,请将localhost替换为远程数据库的IP地址。

Both comments and pings are currently closed.

Comments are closed.

Powered by KingAbc | 粤ICP备16106647号-2 | Loading Time‌ 0.442