Nodejs腳本快速導(dǎo)出MySQL數(shù)據(jù)庫數(shù)據(jù)
說在前面
在數(shù)據(jù)庫管理和數(shù)據(jù)遷移的過程中,常常需要將數(shù)據(jù)庫中的表數(shù)據(jù)和結(jié)構(gòu)進(jìn)行導(dǎo)出,以便進(jìn)行備份、共享或在不同環(huán)境中使用。數(shù)據(jù)庫數(shù)據(jù)備份的方法有很多,今天讓我們用 Node.js 來編寫一個腳本,快速從 MySQL 數(shù)據(jù)庫中導(dǎo)出所有表的數(shù)據(jù)和結(jié)構(gòu),并保存為單獨(dú)的 SQL 文件。
腳本編寫
1. 模塊引入
const mysql = require("mysql");
const fs = require("fs");
mysql模塊用于連接和操作MySQL數(shù)據(jù)庫fs模塊用于文件操作,將數(shù)據(jù)寫入文件。
2. 數(shù)據(jù)庫連接配置
const dbConfig = {
host: "localhost",
user: "root",
password: "password",
database: "test",
};
const connection = mysql.createConnection(dbConfig);
connection.connect((error) => {
if (error) throw error;
console.log("Successfully connected to the database.");
});
定義了數(shù)據(jù)庫連接配置對象dbConfig,包含主機(jī)名、用戶名、密碼和數(shù)據(jù)庫名等信息。然后使用mysql.createConnection創(chuàng)建數(shù)據(jù)庫連接,并通過connection.connect方法進(jìn)行連接,若連接成功則打印相應(yīng)信息。
3. 導(dǎo)出表數(shù)據(jù)和結(jié)構(gòu)的函數(shù)
function exportTableData(tableName, close = false) {
connection.query(
`SHOW CREATE TABLE ${tableName}`,
(error, results, fields) => {
if (error) throw error;
const createTableStatement = results[0]["Create Table"];
connection.query(
`SELECT * FROM ${tableName}`,
(error, results, fields) => {
if (error) throw error;
const insertStatements = results
.map((row) => {
const keys = [],
values = [];
Object.entries(row).forEach((item) => {
keys.push(item[0]);
values.push(`'${item[1]}'`);
});
return `INSERT INTO ${tableName} (${keys.join(
","
)}) VALUES (${values.join(",")});`;
})
.join("\n");
const sql = `${createTableStatement};\n\n${insertStatements}`;
fs.writeFile(`${tableName}.sql`, sql, (err) => {
if (err) throw err;
console.log(`Data from ${tableName} exported successfully.`);
if (close) {
connection.end();
console.log("All exported!");
}
});
}
);
}
);
}
- 這個函數(shù)接受表名
tableName作為參數(shù),還有一個可選參數(shù)close,用于控制是否在導(dǎo)出完成后關(guān)閉數(shù)據(jù)庫連接。 - 首先查詢表的創(chuàng)建語句:
connection.query(
`SHOW CREATE TABLE ${tableName}`,
(error, results, fields) => {
//...
}
);
然后查詢表中的所有數(shù)據(jù):
connection.query(
`SELECT * FROM ${tableName}`,
(error, results, fields) => {
//...
}
);
對于查詢到的數(shù)據(jù),將每行數(shù)據(jù)轉(zhuǎn)換為INSERT INTO語句:
const insertStatements = results
.map((row) => {
const keys = [],
values = [];
Object.entries(row).forEach((item) => {
keys.push(item[0]);
values =append('${item[1]}');
});
return `INSERT INTO ${tableName} (${keys.join(
","
)}) VALUES (${values.join(",")});`;
})
.join("\n");
最后將表的創(chuàng)建語句和所有數(shù)據(jù)的INSERT INTO語句組合起來寫入到以表名命名的.sql文件中:
const sql = `${createTableStatement};\n\n${insertStatements}`;
fs.writeFile(`${tableName}.sql`, sql, (err) => {
if (err) throw err;
console.log(`Data from ${tableName} exported successfully.`);
if (close) {
connection.end();
console.log("All exported!");
}
});
4. 執(zhí)行導(dǎo)出操作
connection.query("SHOW TABLES", (error, results, fields) => {
if (error) throw error;
results.forEach((result, index) => {
const tableName = result[`Tables_in_${dbConfig.database}`];
exportTableData(tableName, index === results.length - 1);
});
});
通過查詢數(shù)據(jù)庫中的所有表,然后對每個表調(diào)用exportTableData函數(shù)進(jìn)行數(shù)據(jù)和結(jié)構(gòu)的導(dǎo)出,當(dāng)處理到最后一個表時,會根據(jù)exportTableData函數(shù)的close參數(shù)設(shè)置來決定是否關(guān)閉數(shù)據(jù)庫連接。
測試
創(chuàng)建數(shù)據(jù)庫
CREATE DATABASE test;
創(chuàng)建表
CREATE TABLE `t_user` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` int NOT NULL, PRIMARY KEY (`id`) )
插入數(shù)據(jù)
INSERT INTO t_user (name,age) VALUES ('張三', 25);
INSERT INTO t_user (name,age) VALUES ('李四', 24);

導(dǎo)出數(shù)據(jù)


到此這篇關(guān)于Nodejs腳本快速導(dǎo)出MySQL數(shù)據(jù)庫數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Nodejs導(dǎo)出MySQL數(shù)據(jù)庫數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
node.js?實(shí)現(xiàn)手機(jī)號驗證碼登錄功能
這篇文章主要介紹了node.js?實(shí)現(xiàn)手機(jī)號驗證碼登錄功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
在windows上用nodejs搭建靜態(tài)文件服務(wù)器的簡單方法
這篇文章主要介紹了在windows上用nodejs搭建靜態(tài)文件服務(wù)器的簡單方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08
node自定義安裝更改npm全局模塊默認(rèn)安裝路徑的步驟
有段時間沒用npm了,新建個項目,需要改變npm全局包默認(rèn)安裝的路徑,本文就來介紹一下node自定義安裝更改npm全局模塊默認(rèn)安裝路徑的步驟,感興趣的可以了解下2021-09-09
vscode調(diào)試node.js的實(shí)現(xiàn)方法
這篇文章主要介紹了vscode調(diào)試node.js的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Node.JS利用PhantomJs抓取網(wǎng)頁入門教程
現(xiàn)今,網(wǎng)頁抓取已經(jīng)是一種人所共知的技術(shù)了,然而依然存在著諸多復(fù)雜性,下面這篇文章主要給大家介紹了Node.JS利用PhantomJs抓取網(wǎng)頁的方法教程,需要的朋友可以參考借鑒,下面來一起看看吧。2017-05-05
Nodejs搭建多進(jìn)程Web服務(wù)器實(shí)現(xiàn)過程
這篇文章主要為大家介紹了Nodejs搭建多進(jìn)程Web服務(wù)器實(shí)現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10

