使用pg模块连接PostgreSQL时提示relation does not exist问题求助
PostgreSQL + pg模块 "关系不存在" 问题排查
问题描述
最近开始学习JavaScript编程,尝试用pg模块和PostgreSQL数据库交互,但明明存在clients表,却一直收到“关系不存在”的错误提示。
代码示例
const Pool = require('pg').Pool const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'test', password: 'test#123', port: '5432', }) pool.query("SELECT * FROM clients", (error, results) => { if (error) throw error console.log(results) }) module.exports = pool
错误信息
错误: 关系"clients"不存在 在 Parser.parseErrorMessage (C:\Users\Maaz\Desktop\Code\acube_backend\node_modules\pg-protocol\dist\parser.js:287:98) 在 Parser.handlePacket (C:\Users\Maaz\Desktop\Code\acube_backend\node_modules\pg-protocol\dist\parser.js:126:29) 在 Parser.parse (C:\Users\Maaz\Desktop\Code\acube_backend\node_modules\pg-protocol\dist\parser.js:39:38) 在 Socket.<anonymous> (C:\Users\Maaz\Desktop\Code\acube_backend\node_modules\pg-protocol\dist\index.js:11:42) 在 Socket.emit (node:events:513:28) 在 addChunk (node:internal/streams/readable:315:12) 在 readableAddChunk (node:internal/streams/readable:289:9) 在 Socket.Readable.push (node:internal/streams/readable:228:10) 在 TCP.onStreamRead (node:internal/stream_base_commons:190:23) { length: 106, severity: 'ERROR', code: '42P01', detail: undefined, hint: undefined, position: '15', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse_relation.c', line: '1384', routine: 'parserOpenTable' }
排查与解决步骤
核对表名与模式
PostgreSQL会把未加双引号的表名自动转为小写。如果你的表实际是Clients或其他大小写混合的名称,必须用双引号包裹表名:SELECT * FROM "Clients"。另外确认表是否在默认的public模式下,若在其他模式,需要指定完整路径:SELECT * FROM 模式名.clients。确认连接的数据库
检查代码里的database: 'test',确保你确实在test数据库中创建了clients表。可以通过psql或pgAdmin登录test数据库,执行\dt命令查看所有表列表。检查用户权限
确保postgres用户拥有clients表的访问权限。执行SQL语句:GRANT ALL ON clients TO postgres;给用户授权(若仅需查询则用GRANT SELECT)。验证连接参数
确认host、port、password均正确,避免连接到了其他PostgreSQL实例(比如本地同时运行了多个版本的PostgreSQL,端口不同)。重启连接池或服务
偶尔连接池可能缓存了旧的元数据,重启Node.js服务或重新初始化连接池,再尝试查询。
内容的提问来源于stack exchange,提问作者Nez
相关产品推荐
相关产品推荐

