Will Rollason
Will Rollason

Reputation: 155

Reading from one db into another

I am trying to right a function that copies some fields from several company databases into my own database once a day. What I have so far is below. I am wondering if where I console.log(rs) I can open another sql connection to my database and write the data or if I have to store the results somewhere and then open a new connection and send the stored results.

function updateJobs() {
  var query = "SELECT JobStart, JobEnd FROM JobData";
  sql.connect(Config, (err) => {
    if (err) {
      console.log("Error while connecting database :- " + err);
    } else {
      var request = new sql.Request();
      request.query(query, function (err, rs) {
        if (err) {
          console.log("Error while querying database :- " + err);
          sql.close();
        } else {
          console.log(rs);
          sql.close();
        }
      })
    }
  })
}

Upvotes: 0

Views: 228

Answers (1)

GRVPrasad
GRVPrasad

Reputation: 1142

This might help

// Source Database
    sourceDB.each(`select * from ${Sourcetable}`, (error, row) => {
            console.log(row);
            const keys = Object.keys(row); // ['columnA', 'columnB']
            const columns = keys.toString(); // 'columnA,columnB'
            let parameters = {};
            let values = '';

// Generate values and named parameters
            Object.keys(row).forEach((r) => {
              var key = '$' + r;
              // Generates '$columnA,$columnB'
              values = values.concat(',', key);
              // Generates { $columnA: 'ABC', $columnB: 'GHK' }
              parameters[key] = row[r];
            });

// Insert into another database into OneTable (columnA,columnB) values ($columnA,$columnB)
            // Parameters: { $columnA: 'ABC', $columnB: 'GHK' }
            destDB.run(`insert into ${Desttable} (${columns}) values (${values})`, parameters);
        })
    })

Upvotes: 0

Related Questions