在Node.js中连接到不同的数据库,你需要使用相应的库。以下是连接到MySQL, PostgreSQL, MongoDB 和 SQLite 数据库的示例代码:
- MySQL: 使用 mysql库
const mysql = require('mysql');
 
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});
 
connection.connect();
 
connection.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});
 
connection.end();- PostgreSQL: 使用 pg库
const { Pool } = require('pg');
 
const pool = new Pool({
  user: 'me',
  host: 'localhost',
  database: 'my_db',
  password: 'secret',
  port: 5432,
});
 
pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res);
  pool.end();
});- MongoDB: 使用 mongodb库
const { MongoClient } = require('mongodb');
 
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
 
async function run() {
  try {
    await client.connect();
    const database = client.db('my_database');
    const collection = database.collection('my_collection');
    const docs = await collection.find({}).toArray();
    console.log(docs);
  } finally {
    await client.close();
  }
}
 
run().catch(console.dir);- SQLite: 使用 sqlite3库
const sqlite3 = require('sqlite3').verbose();
 
let db = new sqlite3.Database('./database.sqlite', (err) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log('Connected to the SQLite database.');
  }
});
 
db.close((err) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log('Close the database connection.');
  }
});确保在使用之前安装对应的npm包,例如使用以下命令安装MySQL、PostgreSQL、MongoDB 和 SQLite 的客户端库:
npm install mysql
npm install pg
npm install mongodb
npm install sqlite3