在 Linux 系統上使用 Node.js 連接數據庫,通常需要遵循以下步驟:
sudo apt-get update
sudo apt-get install mysql-server
npm install mysql
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.connect(error => {
if (error) {
console.error('Error connecting to the database:', error);
return;
}
console.log('Connected to the database successfully!');
// 在這里執行你的數據庫操作,例如查詢、插入、更新等
// 關閉數據庫連接
connection.end();
});
node app.js
這將執行你的代碼并連接到數據庫。如果一切正常,你應該會看到 “Connected to the database successfully!” 的消息。
請注意,這只是一個簡單的示例。在實際應用中,你可能需要處理更復雜的數據庫操作,例如使用 Promise 或 async/await 進行異步操作,以及更好地處理錯誤和異常。