要使用JavaScript讀取MySQL數(shù)據(jù)庫,你需要使用Node.js環(huán)境以及一個名為mysql
的庫。以下是如何設(shè)置并從MySQL數(shù)據(jù)庫中讀取數(shù)據(jù)的步驟:
首先,確保你已經(jīng)安裝了Node.js。如果沒有,請從官方網(wǎng)站下載并安裝:https://nodejs.org/
創(chuàng)建一個新的項目文件夾,然后在該文件夾中打開命令提示符或終端。
運行以下命令以初始化一個新的Node.js項目:
npm init -y
mysql
庫,運行以下命令:npm install mysql
在項目文件夾中創(chuàng)建一個名為app.js
的文件。
編輯app.js
文件,輸入以下代碼:
const mysql = require('mysql');
// 創(chuàng)建與MySQL數(shù)據(jù)庫的連接
const connection = mysql.createConnection({
host: 'localhost', // 數(shù)據(jù)庫服務(wù)器地址,如果數(shù)據(jù)庫在本地,使用'localhost'
user: 'your_username', // 數(shù)據(jù)庫用戶名
password: 'your_password', // 數(shù)據(jù)庫密碼
database: 'your_database' // 要連接的數(shù)據(jù)庫名稱
});
// 連接到數(shù)據(jù)庫
connection.connect((err) => {
if (err) throw err;
console.log('Connected to the database!');
// 查詢數(shù)據(jù)庫
const query = 'SELECT * FROM your_table'; // 更改為你的表名
connection.query(query, (error, results, fields) => {
if (error) throw error;
// 輸出查詢結(jié)果
console.log('Results:', results);
// 關(guān)閉數(shù)據(jù)庫連接
connection.end((err) => {
if (err) throw err;
console.log('Connection closed.');
});
});
});
請確保將上述代碼中的your_username
、your_password
、your_database
和your_table
更改為你的實際數(shù)據(jù)庫信息。
保存app.js
文件,然后在命令提示符或終端中運行以下命令:
node app.js
這就是如何使用JavaScript(通過Node.js)從MySQL數(shù)據(jù)庫中讀取數(shù)據(jù)。