在CentOS上使用Node.js連接數據庫,首先需要確保已經安裝了Node.js和相應的數據庫。以下是連接MySQL數據庫的示例步驟:
如果尚未安裝Node.js,請按照以下命令進行安裝:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
如果尚未安裝MySQL數據庫,請按照以下命令進行安裝:
sudo yum install -y mysql-server
sudo systemctl start mysqld
sudo systemctl enable mysqld
使用MySQL命令行工具創建數據庫和用戶,并授權訪問權限:
mysql -u root -p
輸入密碼后,執行以下SQL語句:
CREATE DATABASE my_database;
CREATE USER 'my_user'@'localhost' IDENTIFIED BY 'my_password';
GRANT ALL PRIVILEGES ON my_database.* TO 'my_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
在Node.js項目中,使用npm安裝mysql驅動:
npm install mysql
創建一個名為app.js
的文件,并編寫以下代碼:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'my_user',
password: 'my_password',
database: 'my_database'
});
connection.connect(error => {
if (error) {
console.error('Error connecting to the database:', error);
return;
}
console.log('Connected to the database.');
// 在這里執行數據庫操作,例如查詢、插入、更新等
connection.end(); // 關閉數據庫連接
});
在終端中運行以下命令啟動Node.js應用程序:
node app.js
如果一切正常,您將看到“Connected to the database.”的輸出?,F在您可以在Node.js應用程序中執行數據庫操作了。