为什么我的查询在pgAdming上工作,但当我从服务器执行它时,我得到一个查询错误(错误:连接终止)

Why is my query working on pgAdming but when I execute it from the server I get a query error (Error: Connection Terminated)?

本文关键字:错误 查询 终止 一个 连接 执行 pgAdming 我的 工作 为什么 服务器      更新时间:2023-09-26

我正在做我的Capstone项目,它需要在数据库中存储一些遥测数据。我使用PostgreSQL 9.5作为数据库,节点作为服务器。

我的问题是,当我试图从服务器发送查询时,我得到一个查询错误[错误:连接终止]。如果我使用JSON.stringify(err),我只看到空括号作为结果{}。有趣的是,如果我使用pgAdmin客户端并执行相同的查询,记录被成功添加,没有任何类型的错误。

这是我在服务器中使用的代码来发送查询:

client.connect(function(err) {
    if(err){
        return console.error('could not connect to postgres', err);
    }
    //Checks if there is survey data to process
    if(surveyFlag){
        //Query to insert survey record
        //Returns survey record's auto-generated id to use it when creating or updating the             //telemetry record in the database 
        var query = 'INSERT INTO survey_response (perceived_risk, actual_risk) '+
                    'VALUES (' + telemetryRecord.survey.perceivedRisk +', ' +                   
                                 telemetryRecord.survey.actualRisk +') ' +
                    'RETURNING survey_id';
        client.query(query, function(err, result) {
        console.log("Query: " + query);
                if(err) {
                    console.log(err);
                    return console.error('error running survey query', err);
                }
                surveyID = result.rows[0].survey_id;    
                //Testing
                console.log ("Survey response added with ID: " + surveyID);

        });
            //Close the connection  
        client.end();
});

代码client.end()与代码client.query()放在同一级别。由于client.query()是异步的,因此在启动查询后立即调用client.end()。当查询返回时,客户端已经结束,这导致了问题。

尝试将client.end()代码放在client.query()的回调函数中。

client.query(query, function(err, result) {
  console.log("Query: " + query);
  if(err) {
    console.log(err);
    return console.error('error running survey query', err);
  }
  surveyID = result.rows[0].survey_id;    
  //Testing
  console.log ("Survey response added with ID: " + surveyID);
  //Close the connection  
  client.end();
});