首页 > 解决方案 > 截断临时表,加载 XML 文件数据,然后使用 Node.js 从 Mysql 中的临时表插入主表

问题描述

我需要截断一个临时表,然后将 XML 文件加载到该表中,并且需要从该表中将数据插入到主表中,但是我能够加载到临时表中并插入到主表中,但是只要我添加代码截断表,表被截断,文件被加载到临时表中,但主表中没有插入。感谢帮助。

const dir = "./files/06-09-2021";
const runProcess = async () => {
  try {
    await checkDir();
    await trunTempQuery();
    const dirResult = await readDir();
    await loadTempData(dirResult);
    await loadData();
    await sendResponse(dirResult);
  } catch (err) {
    console.error(err);
    res.send("Some error: please check console on application");
  }
};

const trunTempQuery = async () => {
  console.log("in truncate query");
  await pool.promise().query({
    sql: `TRUNCATE TABLE mobileright.blk_temp;`,
  });
};
const readDir = async () => {
  return await fs.readdir(dir, "utf8");
};
const checkDir = async () => {
  return await fs
    .ensureDir(dir)
    .then(() => {
      console.log("Files Found");
    })
    .catch((err) => {
      console.error(err);
    });
};

const loadData = async () => {
  console.log("In loadData");
  return await pool.promise().query({
    sql: `INSERT INTO mobileright.sms_blk_lists(MSISDN_vch,MSISDNEvent_vch,timeStamp_dt,changeID_vch,MSISDNNew_vch,operatorID_vch)
              SELECT MSISDN,MSISDNEvent,timeStamp,changeID,MSISDNNew,operatorID
              FROM mobileright.blk_temp`,
  });
};

const loadTempData = async (dirResult) => {
  console.log("In loadTempData");
  try {
    if (!dirResult.length) {
      console.log(dirResult);
      res.send("No files for today");
    } else {
      await dirResult.forEach(async (file) => {
        return await pool.promise().query({
          sql: "LOAD XML LOCAL INFILE ? INTO TABLE mobileright.blk_temp ROWS IDENTIFIED BY ?",
          values: [
            "C:/work/blacklisting/files/06-09-2021/" + file,
            "<MSISDNChange>",
          ],
          infileStreamFactory: () =>
            fs.createReadStream(
              "C:/work/blacklisting/files/06-09-2021/" + file
            ),
        });
      });
    }
  } catch (err) {
    console.log(err);
  }
};
const sendResponse = (dirResult) => {
  console.log("response sent");
  res.send({ dirResult });
};
runProcess();

标签: javascriptmysqlnode.jsdatabase

解决方案


推荐阅读