[英]How do I properly insert multiple rows into PG with node-postgres?
[英]Outputting rows from the pg module in Node / Postgres
在我的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'])已成功將表名稱輸出到控制台。 但是,看起來閉包中既沒有響應變量也沒有我...那么我到底該如何獲取查詢結果來處理呢?
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();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.