在我的Node应用程序中,我想连接到postgresql数据库以对这些实体进行一些操作。但我无法让它与Node一起工作。我已经使用psycopg2从Python脚本成功连接并查询了数据库,所以我知道连接部分可以工作。
var DB_URL = "postgres://admin@localhost/mydb_development"
var db = new pg.Client(DB_URL);
db.connect();
.... more stuff here ....
app.get('/test', function(request, response) {
response.setHeader('Content-Type', 'text/plain');
response.write("First!\n");
var i = 0;
var query = db.query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'", []);
query.on('row', function(row) {
console.log(row['table_name']);
i++;
response.write(String(row['table_name']) + "\n");
});
response.write("\nHello db; variable i=" + i + "!");
response.end();
});
我发现console.log(row ['table_name'])成功地将表名输出到控制台。但是,看起来封闭内部的响应变量和i都不可用......那么我应该如何得到查询的结果呢?!
答案 0 :(得分:1)
response
变量可用但不可写,因为您已end
编辑它。
i
也应该可用,但在您将其写入回复时,它尚未增加。
在获得所有行之后,您可能想要end
(并写下最后一行)。它可以这样实现:
var DB_URL = "postgres://admin@localhost/mydb_development"
var db = new pg.Client(DB_URL);
db.connect();
.... more stuff here ....
app.get('/test', function(request, response) {
response.setHeader('Content-Type', 'text/plain');
response.write("First!\n");
var i = 0;
var query = db.query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'", []);
query.on('row', function(row) {
console.log(row['table_name']);
i++;
response.write(String(row['table_name']) + "\n");
});
query.on('end', function () {
response.write("\nHello db; variable i=" + i + "!");
response.end();
});
});