简体   繁体   English

如何从NodeJS连接到PostgreSQL

[英]How to connect to PostgreSQL from NodeJS

I am trying to connect to a PostgreSQL database and make some queries. 我正在尝试连接到PostgreSQL数据库并进行一些查询。 Though I have read a few threads here, the docs, and other blogs, I'm unable to make it works. 尽管我在这里阅读了一些主题,文档和其他博客,但我无法使其正常运行。

My function looks like this: 我的函数如下所示:

 const postgreSQL = require('pg'); const config = { host: 'host', database: 'db', user: 'user', password: 'pass', port: 0000, max: 5, // max number of clients in the pool idleTimeoutMillis: 30000 }; let pool = new postgreSQL.Pool(config); //.........other code......... function CheckGeometryType(pool, tableName, column) { const schema = 'schema'; let geometryValue = undefined; pool.connect(function(err, client, done) { client.query(`SELECT ST_GeometryType(${column}) AS geometryType FROM ${schema}.${tableName} LIMIT 1`); done(err); if (err) { console.log('Something went wrong. ' + err); } console.log("Result: " + queryResult.rows[0]); switch (queryResult) { // do things with result } done(); }); return geometryValue; } 

I've tried to do a console.log() inside the SWITCH , after/before done() , but it's not executed. 我已经尝试在done()之后/之前在SWITCH内执行console.log() () ,但未执行。 I have printed all SQL queries formed on the string I pass to pool.query on pgAdmin and all works and return the expected values I want to get. 我已经打印了在传递给pgAdminpool.query的字符串上形成的所有SQL查询,并且所有工作都返回了我想要得到的期望值。

What am I doing wrong? 我究竟做错了什么?

Thanks! 谢谢!

--- Edit --- -编辑-

Thanks for the answers, but I'm still being unable to make it work. 感谢您的回答,但我仍然无法使其正常工作。 I've tried both methods but it isn't works. 我已经尝试了两种方法,但是都行不通。 Looking at the Documentation I'm trying this method. 查看文档,我正在尝试这种方法。

The code is: 代码是:

 let client = new Client(connectionString); client.connect(); const query = client.query(new Query('SELECT ST_GeometryType($1) FROM $2.$3 LIMIT 1', [column, schema, tableName])); console.log(JSON.stringify(query, null, 2)); //Debug purposes query.on('row', (row) => { switch (row[0]) { case 'ST_LineString': geometryValue = 'LineString'; break; case 'ST_MultiLineString': geometryValue = 'MultiLineString'; break; case 'ST_Polygon': geometryValue = 'Polygon'; break; case 'ST_MultiPolygon': geometryValue = 'MultiPolygon'; break; case 'ST_Point': geometryValue = 'Point'; break; case 'ST_MultiPoint': geometryValue = 'MultiPoint'; break; default: break; } }); query.on('end', (res) => { if(result.rows[0] === undefined){ console.log('No data retrieved from DB'); } client.end(); }); query.on('error', (res) => { console.log("Something went wrong: " + res); }); 

Debugging, I can see that on query the values are stored fine: 调试时,我可以看到在查询时值存储得很好:

{
  "text": "SELECT ST_GeometryType($1) FROM $2.$3 LIMIT 1",
  "values": [
    "column",
    "schema",
    "table"
  ],
  "portal": "",
  "_result": {
    "command": null,
    "rowCount": null,
    "oid": null,
    "rows": [],
    "fields": [],
    "_parsers": [],
    "RowCtor": null,
    "rowAsArray": false
  },
  "_results": {
    "command": null,
    "rowCount": null,
    "oid": null,
    "rows": [],
    "fields": [],
    "_parsers": [],
    "RowCtor": null,
    "rowAsArray": false
  },
  "isPreparedStatement": false,
  "_canceledDueToError": false,
  "_promise": null,
  "domain": null,
  "_events": {},
  "_eventsCount": 0
}

I've executed the query on pgAdmin an works fine, returning the desired result that I'm expecting but seems that trying to execute the query on the script doesn`t works. 我已经在pgAdmin上执行了查询,效果很好,返回了我期望的期望结果,但是似乎无法在脚本上执行查询。

What I'm missing? 我想念的是什么? Thanks. 谢谢。

You can also use raw acces with "pg" package: 您还可以将原始acces与“ pg”包一起使用:

pg.connect(connectionString, function (err, client, done) {
  if (err) {
    return handleErrors(done, err, res);
  }
  return client.query("UPDATE tab SET v1=($1)  WHERE k1=($2)", [value, key], 
    function (err, result) {
     return reloadData(res, client, done, err);
  });
});

You can use sequelize for PostgreSQL. 您可以对PostgreSQL使用sequelize。 Its very good Object-Relational Mapping(ORM) in Node.js. Node.js中非常好的对象关系映射(ORM)。

const sequelize = new Sequelize('database', 'username', 'password', { // gimme postgres, please! dialect: 'postgres' }) const sequelize = new Sequelize('database','username','password',{// gimme postgres,请!方言:'postgres'})

for more details check below link. 有关更多详细信息,请检查下面的链接。 http://docs.sequelizejs.com/manual/installation/usage.html http://docs.sequelizejs.com/manual/installation/usage.html

Well, finally I did achieve what I want to do. 好吧,终于我实现了我想要做的事。 After read more the documentation and use the new methods (some questions had the old version, Node version < 7.x) I finally made it work. 在阅读了更多文档并使用了新方法之后(有些问题是旧版本,Node版本<7.x),我终于使它起作用了。 I'm posting the solution to help someone who may have the same problem building their own script. 我正在发布解决方案,以帮助可能在构建自己的脚本时遇到相同问题的人。

This method uses the async/await form, so keep in mind that you will have to set all your functions to async and set await to the function that waits for the result inside of it, it's a chain from the function that connects with the DB to the top. 此方法使用async / await形式,因此请记住,必须将所有函数设置为async并将await设置为等待其内部结果的函数,这是与数据库连接的函数的链到顶部。

 # Main file #!/usr/bin/env node 'use strict'; const geometryTypeFinder = require("./modules/geometryTypeFinder"); readParametersFromConsole(); async function readParametersFromConsole() { ........ code ........ processParameters(...params); } async function processParameters(...params) { ........ code ........ transformation = await geometryTypeFinder.findGeometryType(transformation); ........ code ........ } # Module file 'use strict'; const postgreSQL = require('pg'); module.exports = { findGeometryType: async function (transformation) { ........ code ........ transformation.dataModel.entities = await FindGeometryType(...params); ........ code ........ } }; async function FindGeometryType(entities, geometricColumns) { ........ code ........ for (let i = 0; i < numberOfEntities; i++) { ........ code ........ for (let j = 0; j < numberOfColumns; j++) { let column = columns[j]; let geometryType = await GetGeometryType(tableName, column); ........ now I can work with the value of geometryType ........ } } } async function GetGeometryType(tableName, column) { const schema = 'schema'; let geometryValue = undefined; const config = { user: 'user', password: 'pass', host: 'host', database: 'db', port: 1234, }; let client = new postgreSQL.Client(config); try { client.connect(); const result = await client.query(`SELECT ST_GeometryType(${column}) AS geo_type FROM ${schema}.${tableName} LIMIT 1`); if (result.rows.length === 0) { console.log('No data retrieved from DB'); } else { const geoType = result.rows[0].geo_type; #<--- I get the result ........ code to process the value ........ } } catch (error) { console.log(`Error retrieving database information: ${error.name} -> ${error.stack}`); } finally { client.end(); } return geometryValue; } 

I don't know if this it's the best way to achieve what I want, but as I'm forced to use NodeJS and I'm learning by myself NodeJS, this is the best I could make it. 我不知道这是否是实现我想要的最好的方法,但是由于我被迫使用NodeJS,而我自己学习NodeJS,所以这是我能做到的最好的方法。 Any suggestion will be well received. 任何建议都会受到欢迎。

Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM