在Debian上使用Node.js连接数据库,通常需要遵循以下步骤:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
这里我们安装的是Node.js 14.x版本,你可以根据需要选择其他版本。
sudo apt-get install -y libmysqlclient-dev
npm install mysql
sudo apt-get install -y libpq-dev
npm install pg
npm install mongodb
sudo apt-get install -y sqlite3 libsqlite3-dev
npm install sqlite3
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('Connected to the MySQL database.');
});
// Your database operations go here
connection.end();
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('Connected to the PostgreSQL database.');
});
// Your database operations go here
client.end();
const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb://localhost:27017/your_database';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(error => {
if (error) throw error;
console.log('Connected to the MongoDB database.');
});
// Your database operations go here
client.close();
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('your_database.db', error => {
if (error) throw error;
console.log('Connected to the SQLite3 database.');
});
// Your database operations go here
db.close();
node app.js
这将执行你的代码并连接到指定的数据库。如果一切正常,你应该会看到类似于上面的示例中的连接成功消息。