我正试图从两个不同数据库的表中获得合并结果.koajs和Node.js是我的新手。 以下是我正在尝试的示例代码:
db / index.js
const { Pool } = require('pg')
const pool = new Pool({
host: 'localhost',
port: '5432',
user: 'postgres',
password: 'postgres',
database: 'sampl',
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
const pool1 = new Pool({
host: 'localhost',
port: '5432',
user: 'postgres',
password: 'postgres',
database: 'secon',
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
我使用的路由文件[/route.js]
import Router from 'koa-router'
const router = new Router()
var someVar = [];
var internas = [];
const db = require('../db')
router.get('/samson', ctx => {
db.query('SELECT * FROM sam', null, (err, res) => {
if (err) {
console.log(err);
}
for (var i = 0; i < res.rowCount; i++) {
var sno = res.rows[i].sno;
var name = res.rows[i].name;
var mobile = res.rows[i].mobile;
var indx = i + 1;
internas[i] = setValue(res.rows[i], i);
console.log(internas);
db.squery('SELECT * FROM dtl where sno=$1', [sno], (err, resu) => {
if (err) {
console.log(err);
} else {
var salary = resu.rows[0].salary;
var address = resu.rows[0].address;
console.log(someVar);
}
})
}
})
ctx.body = internas;
})
function setValue(value, index) {
var someVars = value;
return someVars;
}
export default router
我正试图将两个数据库中的两个表合并为一个请求
Table 1 contain: sno, name, mobile
Table 2 contain: sno, salary, address
我期望对表1中的每条记录都需要从表2中获取 输出将像
Record1: sno, name, mobile, salary, address
record2: sno, name, mobile, salary, address
请建议,我以前是同步编程的,这是异步的
答案 0 :(得分:0)
您可以改用pg-promise,并使用async / await来使您的生活更轻松,并执行一些使它性能更高的任务。
const { Pool } = require('pg-promise')
router.get('/samson', async ctx => {
try{
db.task('my-es7-task', async t => {
let res = await t.any('SELECT * FROM sam', null);
for (var i = 0; i < res.rowCount; i++) {
try{
var sno = res.rows[i].sno;
var name = res.rows[i].name;
var mobile = res.rows[i].mobile;
var indx = i + 1;
internas[i] = setValue(res.rows[i], i);
console.log(internas);
let results = await t.any('SELECT * FROM dtl where sno=$1', [sno])
var salary = resu.rows[0].salary;
var address = resu.rows[0].address;
console.log(someVar);
}catch(e){
console.log(e);
}
}
ctx.body = internas;
}
}catch(e){
console.log(e);
}
})