gpt4 book ai didi

node.js - postgres 中的查询问题

转载 作者:行者123 更新时间:2023-11-29 13:40:38 25 4
gpt4 key购买 nike

我在 Node.js 应用程序中使用以下代码片段来尝试查询(本地)postgres 数据库:

   var conString = "postgres://user:password@localhost:5432/mydatabase";
var client = new pg.Client(conString);

client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query("SELECT * FROM users WHERE name = $1 AND cred = $2", [String(req.body.usr), String(req.body.pword)], function(err, result) {
if(err) {
return console.error('error running query', err);
}
if (typeof result.rows[0] === "undefined") {
console.log("No user/password determined in DB for login attempt");
} else {

} //user/password is 'undefined' (NOT found in database)...OR NOT...

client.end();
});
});

我在查询运行时收到错误...我认为问题可能出在我的查询调用中的参数数量...?如果是这种情况(或者是其他一些语法问题),有人可以告诉我应该如何更改代码以正确执行查询......?

我只需要从表单(req.body.usr 和 req.body.pword)中获取 2 个(用户提供的)结果,并将它们与数据库表“用户”进行比较以确定凭据是否正确。我已经相信数据库连接正常。非常感谢任何建议。提前谢谢你。

最佳答案

改变:

client.query("SELECT * FROM users WHERE name = $1 AND cred = $2", [String(req.body.usr), String(req.body.pword)], function(err, result) {...

到:

const query = {
text: "SELECT * FROM users WHERE name = $1 AND cred = $2",
values: [String(req.body.usr), String(req.body.pword)]
};
client.query(query, function(err, result) {

阅读更多:https://node-postgres.com/features/queries

关于node.js - postgres 中的查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55875870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com