我试图了解pool.query
和client.query
以及两者之间的区别以及何时使用它们。
我有一个Express应用程序,该应用程序在某个端点上运行以下代码。
// am just using params for to a quick setup
router.get("/:username/:password", (req, res) => {
const { username, password } = req.params;
// crypt & gen_salt function from pgcrypto
pool // *** here ***
.query(
` SELECT username, email, password FROM users
WHERE users.username = $1
AND users.password = crypt($2, password)
`, [username, password]
)
.then(user => {
console.log("Users ==>", user.rows);
const userCount = user.rows.length;
if (userCount < 1) {
res.status(204).json({ userFound: "No User Found" });
} else {
res.status(200).json(user.rows[0]);
}
})
.catch(err => console.log(err));
});
// am just using params for to a quick setup
router.get("/:username/:password", (req, res) => {
const { username, password } = req.params;
// crypt & gen_salt function from pgcrypto
client // *** here ***
.query(
` SELECT username, email, password FROM users
WHERE users.username = $1
AND users.password = crypt($2, password)
`, [username, password]
)
.then(user => {
console.log("Users ==>", user.rows);
const userCount = user.rows.length;
if (userCount < 1) {
res.status(204).json({ userFound: "No User Found" });
} else {
res.status(200).json(user.rows[0]);
}
})
.catch(err => console.log(err));
});
// index.js (starting point of application)
require("dotenv").config({ debug: true });
const app = require("./middleware");
// Port Listener
app.listen(process.env.PORT, () =>
console.log(
"Server running on PORT <======= " + process.env.PORT + " =======>"
)
);
我击中了API端点,并且两种方式都返回了完全相同的结果,并且我读到使用池化实例化一个新的客户端实例会更好,但是老实说我不确定这是否成立,因为Node应该保持同一客户端实例,因为它的导出方式超出了我当前的知识范围。我在该主题上发现的读物很少,因此,如果有人推荐他们的文章,那么我也很乐意将它们检查出来。
答案 0 :(得分:1)
我相信两者都是一样的。但是pool.query
允许您在需要从客户端线程池访问的客户端执行时执行基本的单个查询。
因此pool.query
可用于直接运行查询,而不是获取客户端,然后使用该客户端运行查询。
从池中获取客户端
const { Pool } = require('pg')
const pool = new Pool()
pool.connect((err, client, release) => {
if (err) {
return console.error('Error acquiring client', err.stack)
}
client.query('SELECT NOW()', (err, result) => { // Default client query which is same as that used when connect to DB with one client.
release()
if (err) {
return console.error('Error executing query', err.stack)
}
console.log(result.rows)
})
})
与上述相同,但没有游泳池
const { Client } = require('pg').Client
const client = new Client()
client.connect()
client.query('SELECT NOW()', (err, res) => {
if (err) throw err
console.log(res)
client.end()
})
直接在池中调用查询
const { Pool } = require('pg')
const pool = new Pool()
// Direct query without acquiring client object.
pool.query('SELECT $1::text as name', ['brianc'], (err, result) => {
if (err) {
return console.error('Error executing query', err.stack)
}
console.log(result.rows[0].name) // brianc
})