在 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 进行异步操作,以及更好地处理错误和异常。