通过 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);
注意事项