我试图让pg-promise在NodeJS工作,让我连接到我的PostgreSQL数据库。node和postgre都在运行Ubuntu的codeanywhere节点箱中运行。
相关代码如下:
var pgp = require('pg-promise')();
var bot = new TelegramBot(token, { polling: true });
var db = pgp({
host: 'localhost',
port: 5432,
database: 'users',
user: 'postgres',
password: '(pass here)'
});
db.any("select * from users")
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
运行node bot.js
打印如下:
{ [error: relation "users" does not exist]
name: 'error',
length: 96,
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: '984',
routine: 'parserOpenTable' }
并将以下内容打印到/var/log/postgresql/postgresql-9.3-main.log
:
2016-09-29 23:09:29 EDT ERROR: relation "users" does not exist at character 15
我做错了什么?我想它应该与db.any()有关,因为下面的代码可以工作:
//db.any("select * from users")
db.connect()
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
输出是一个返回的东西,看起来大约像db
对象,但这不是我需要的…
我看到其他stackoverflow问题提到大写是一个问题。具体来说,他们说postgresql将使您的输入全部小写,不带双引号。消除任何相关的概念:
postgres=# dt
List of relations
Schema | Name | Type | Owner
--------+-------+-------+----------
public | users | table | postgres
(1 row)
这种关系确实存在。
我错过了什么?
错误告诉您数据库中没有users
表。您需要先创建表,然后才能从中进行选择。请记住,表名是区分大小写的,所以如果您创建了一个Users
表,您的查询将无法工作。
CREATE TABLE Users (...);
SELECT * FROM users; -- this will cause an error
您应该尝试在命令行中使用psql -d users
(在本例中,users
是数据库的名称,不要与同名表混淆)连接到数据库。从那里,您可以编写查询来独立于应用程序代码进行测试。如果你在连接users
数据库时遇到问题,你可以使用psql连接到默认数据库,并输入l
或list
来列出postgres知道的所有数据库。
请注意,Postgres本身有一个名为postgres
的内置数据库,它有自己的users
表来管理对其他数据库的访问控制。你可以通过查看命令提示符来判断你在psql中连接到哪个数据库;如果显示的是postgres=
,那么你在postgres数据库中,而不是你自己的。