通过 JavaScript 连接远程数据库的方法:MySQL:使用 MySQL Connector/J 库连接 MySQL 数据库。PostgreSQL:使用 pg 库连接 PostgreSQL 数据库。MongoDB:使用 MongoDB Node.js Driver 库连接 MongoDB 数据库。

如何使用 JavaScript 连接远程数据库
简介
通过 JavaScript 连接远程数据库可以实现前端与后端数据的交互。本文将介绍使用 JavaScript 连接常见远程数据库的方法,包括 MySQL、PostgreSQL 和 MongoDB。
方法
1. MySQL
使用 MySQL Connector/J 库连接 MySQL 数据库:
import { createConnection } from 'mysql';
const connection = createConnection({
host: 'remote-host',
user: 'username',
password: 'password',
database: 'database_name'
});
connection.connect();
connection.query('SELECT * FROM table', (err, rows) => {
if (err) throw err;
console.log(rows);
});2. PostgreSQL
使用 pg 库连接 PostgreSQL 数据库:
import { Client } from 'pg';
const client = new Client({
host: 'remote-host',
user: 'username',
password: 'password',
database: 'database_name'
});
await client.connect();
const res = await client.query('SELECT * FROM table');
console.log(res.rows);3. MongoDB
使用 MongoDB Node.js Driver 库连接 MongoDB 数据库:
import { MongoClient } from 'mongodb';
const client = await MongoClient.connect('mongodb://remote-host:27017');
const db = client.db('database_name');
const collection = db.collection('collection_name');
const docs = await collection.find({}).toArray();
console.log(docs);注意事项
- 确保已安装所需的库。
- 用正确的连接详细信息(主机、用户名、密码等)替换占位符。
- 处理错误和异步操作(例如使用
async/await或回调)。 - 在不再需要时关闭数据库连接。










