龙空技术网

Node.js,连接MySQL,从数据表中复制数据,异步方法转同步方法

古怪今人 251

前言:

现在小伙伴们对“mysql复制表数据到另一张表”大体比较珍视,姐妹们都想要剖析一些“mysql复制表数据到另一张表”的相关内容。那么小编也在网络上汇集了一些有关“mysql复制表数据到另一张表””的相关文章,希望姐妹们能喜欢,看官们快快来学习一下吧!

说明

Node.js,连接MySQL,将数据从MySQL数据库的一张表复制到另一张表中,安装驱动:npm install mysql --save

代码实现

module/src.js

const mysql = require('mysql');exports.createConnection = function(){  return connection = mysql.createConnection({    host: '127.0.0.1',    user: 'root',    password: 'root1234',    port: '3306',    database: 'database1',  });}exports.connect = function(connection){  connection.connect(function (error) {    if (error) {      console.log('[query] - :' + error);      return;    }    console.log('[src][connection connect]  succeed!');  });}exports.close = function (connection) {  connection.end(function (error) {    if (error) {      return;    }    console.log('[src][connection end] succeed!');  });}

module/target.js

const mysql = require('mysql');exports.createConnection = function(){  return connection = mysql.createConnection({    host: '127.0.0.1',    user: 'root',    password: 'root1234',    port: '3306',    database: 'database2',  });}exports.connect = function(connection){  connection.connect(function (error) {    if (error) {      console.log('[query] - :' + error);      return;    }    console.log('[target][connection connect]  succeed!');  });}exports.close = function (connection) {  connection.end(function (error) {    if (error) {      return;    }    console.log('[target][connection end] succeed!');  });}

main.js

const mysql = require('mysql');const srcMySQLConnect = require('./module/src');const targetMySQLConnect = require('./module/target');// 连接源MySQLlet srcConnect = srcMySQLConnect.createConnection();srcMySQLConnect.connect(srcConnect);//console.log('srcConnect', srcConnect);// 连接目标MySQLlet targetConnect = targetMySQLConnect.createConnection();targetMySQLConnect.connect(targetConnect);// console.log('targetConnect', targetConnect);// 复制数据function swapData(srcConnect, targetConnect) {  let selectSql = "select * from health_manufactor";  srcConnect.query(selectSql, function (error, result, fields) {    if (error) {      throw error;    }    if (result.length > 0) {      result.forEach(item => {        console.log("item", item);        let addSql = `INSERT INTO goods_manufactor(          id,manufactor_code,manufactor_name,address,phone,          sorted,remark,status,logical_deleted,create_uid,          create_user,create_time,modified_user,modified_time        )        VALUES(            ?,?,?,?,?,            ?,?,?,?,?,            ?,?,?,?        )`;        let addSqlParams = [          item.id, item.manufactor_code, item.manufactor_name, item.address, '',          1, '', 1, 0, 0,          'system', new Date(), 'system', new Date()        ];        targetConnect.query(addSql, addSqlParams, function (addErr, addResult) {          if (addErr) {            console.log(addErr);            throw addErr;          }          console.log('addResult.insertId:', addResult.insertId);        });      });    }  });}swapData(srcConnect, targetConnect);// 关闭连接// 解决:Error: Cannot enqueue Query after invoking quit.// targetMySQLConnect.close(targetConnect);// srcMySQLConnect.close(srcConnect);
异步方法转同步方法按序执行

main.js

const srcMySQLConnect = require('./module/src');const targetMySQLConnect = require('./module/target');// 创建连接async function createConnect() {  // 连接源MySQL  let srcConnect = await srcMySQLConnect.createConnection();  await srcMySQLConnect.connect(srcConnect);  // 连接目标MySQL  let targetConnect = await targetMySQLConnect.createConnection();  await targetMySQLConnect.connect(targetConnect);  return {    srcConnect: srcConnect,    targetConnect: targetConnect,  }}// 查询数据async function queryData(connect, queryFunc) {  let selectSql = "select * from health_manufactor";  await connect.query(selectSql, queryFunc);}// 插入数据async function insertData(connect, item, queryFunc) {  let addSql = `INSERT INTO goods_manufactor(    id,manufactor_code,manufactor_name,address,phone,    sorted,remark,status,logical_deleted,create_uid,    create_user,create_time,modified_user,modified_time  )  VALUES(      ?,?,?,?,?,      ?,?,?,?,?,      ?,?,?,?  )`;  let addSqlParams = [    item.id, item.manufactor_code, item.manufactor_name, item.address, '',    1, '', 1, 0, 0,    'system', new Date(), 'system', new Date()  ];  await connect.query(addSql, addSqlParams, queryFunc);}// 关闭连接async function close(data) {  targetMySQLConnect.close(data.targetConnect);  srcMySQLConnect.close(data.srcConnect);}function main() {  createConnect().then(v => {    console.log("=====1=====");    return new Promise((resolve, reject) => {      queryData(v.srcConnect, function (error, result, fields) {        if (error) {          throw error;        }        v.data = result;        resolve(v);      });    })  }).then(v => {    console.log("=====2=====", v.data.length);    return new Promise((resolve, reject) => {      for (let i = 0; v.data.length && i < v.data.length; i++) {        insertData(v.targetConnect, v.data[i], function (addErr, addResult) {          if (addErr) {            console.log(addErr);            throw addErr;          }          console.log('addResult.insertId:', addResult.insertId);        });      }      resolve(v);    });  }).then(v => {    console.log("=====3=====", "关闭连接");    close(v);  });}main();

标签: #mysql复制表数据到另一张表