简体   繁体   中英

Node.js and Heroku, how to insert a second query?

I am working with Node.js and Heroku; and I have a question about the following code, that I found online:

app.get('/db', function (request, response) {
  pg.connect(process.env.DATABASE_URL, function(err, client, done) {
    client.query('SELECT * FROM test_table', function(err, result) {
      done();
      if (err)
       { console.error(err); response.send("Error " + err); }
      else
       { response.render('pages/db', {results: result.rows} ); }
    });
  });
});

This lists the contents of the test_table table, but I also want to perform the following query:

*"INSERT INTO test_table (fieldOne, fieldTwo) VALUES (MAX(fieldOne)+1, MAX(fieldTwo) 2)"

How can I integrate this in the code above?

Here is something I tried, but with no success:

app.get('/db', function (request, response) {
  pg.connect(process.env.DATABASE_URL, function(err, client, done) {
    client.query('SELECT * FROM test_table', function(err, result) {
      done();
      if (err)
       { console.error(err); response.send("Error " + err); }
      else { 
        response.render('pages/db', {results: result.rows} ); 
        client.query("INSERT INTO test_table  (id, name) VALUES (MAX(id)+1,'TEST')", function(err, result) {done();});
      }
    });
  });
});

I don't know if this last chunk of code is almost right or totally wrong. But all I can say is that the DB table (test_table) is not updated.

In case it might help someone else, I post here the change I made to have my code work:

app.get('/db', function (request, response) {
  pg.connect(process.env.DATABASE_URL, function(err, client, done) {
    client.query('SELECT * FROM test_table', function(err, result) {
      done();
      if (err)
       { console.error(err); response.send("Error " + err); }
      else { 
        response.render('pages/db', {results: result.rows} ); 
        client.query("INSERT INTO test_table  (id, name) VALUES ((SELECT MAX(id) FROM test_table)+1,'TEST')", function(err2, result2) {done();});
      }
    });
  });
});

There must be other things to be said about this, but at least it now works.

This answer is meant in case some developers trying to get their hands on Node.js hit the same questions I did. Here is a tiny site I made, as a use case, in order to get some practice. I am showing hereafter the relevant code. It will hopefuly help someone later.

Reading Getting Started on Heroku with Node.js I got my hands on the subject.

I started from this as suggested in the document mentioned above.

Here are the relevant changes I made to the top index.js file:

app.get('/', function (request, response) {
  pg.connect(process.env.DATABASE_URL, function(err, client, done) {
    client.query('SELECT * FROM Prime_List ORDER BY rank', function(err, result) {
      done();
      if (err)
       { console.error(err); response.send("Error " + err); }
      else { 
         client.query('SELECT * FROM Leap_List ORDER BY rank', function(err, resultLeap) {
           done();
           if (err) {console.error(err); response.send("Error " + err);}
           else {
             response.render('pages/index', {results: result.rows, resultsLeap:resultLeap.rows, ua:agent} );
             lastPrime=result.rows[result.rows.length-1].prime;
             newPrime=getNextPrime(result.rows);
             client.query("INSERT INTO Prime_List (rank,prime) VALUES ((SELECT MAX(rank) FROM Prime_List)+1,"+newPrime+")", 
             function(err, result2) {
              done();
              if (err){ console.error(err); response.send("Error " + err); }
              else {
                client.query("SELECT COUNT(*) FROM Leap_List WHERE (leap="+(newPrime-lastPrime)/2+")",
                function(err, resultCnt) {
                  done();
                  if (err) { console.error(err); response.send("Error " + err); }
                  else {
                    if (resultCnt.rows[0].count==1) {
                      client.query("UPDATE Leap_List SET count=count+1 WHERE (leap="+(newPrime-lastPrime)/2+")",
                        function(err, resultUpd) {
                          done();
                          if (err) { console.error(err); response.send("Error " + err); }
                      });
                    } else /*(resultCnt[0]==0)*/ {
                      leapQuery="INSERT INTO Leap_List (rank,leap,initial,final,count) VALUES";
                      leapQuery+=" ((SELECT MAX(rank) FROM Leap_List)+1,";
                      leapQuery+=(newPrime-lastPrime)/2+",";
                      leapQuery+=lastPrime+",";
                      leapQuery+=newPrime+",";
                      leapQuery+="1)";
                      client.query(leapQuery,
                      function(err, resultUpd) {
                        done();
                        if (err) { console.error(err); response.send("Error " + err); }
                      });
                    }}});
              }});
           }});
      }});
  });
});


function getNextPrime(primeList) {
  var resultPrime = primeList[primeList.length-1].prime + 2;

  do {for (i=1; i<primeList.length; i++) {
        if (primeList[i].prime*primeList[i].prime>resultPrime) return resultPrime;
        if (resultPrime%primeList[i].prime == 0) break;
      }
      resultPrime+=2;
  } while (true);
}

Here are the relevant modifications I made to the views/pages/index.ejs file (version using tables):

First table (the prime numbers):

<table cellspacing=5>
    <% var npr=15; i=0; results.forEach(function(r) {
        if ((i==90)&&(npr==15)) { npr--; i=0; %> </table><br/><table> <% }
        if ((i==70)&&(npr==14)) { npr--; i=0; %> </table><br/><table> <% }
        if (i%npr==0) { %> <tr align=right> <% } %>
        <td bgcolor=#FFFF66><%= r.rank %></td><td bgcolor=#66FF66><font color=#000080><%= r.prime %></font></td>
        <% if (i%npr==(npr-1)) { %> </tr> <% } %>
        <% i++; %>
    <% }); %>
</table>

Second table (the leaps):

<table cellspacing=5>
<tr align=center>
<td bgcolor=#FFAAFF>Rank</td><td bgcolor=#FFAAFF>Leap</td>
<td bgcolor=#FFAAFF>Count</td><td  bgcolor=#FFAAFF colspan=2>First case</td>
</tr>
    <% var npr=5; i=0; total=0;
      resultsLeap.forEach(function(r) { 
        total+=r.count; %>
        <tr align=right>
        <td bgcolor=#FFFF99><%= r.rank %></td>
        <td bgcolor=#EEDD88><font color=#000080><%= r.leap %></font></td>
        <td bgcolor=#EEDD88><font color=#000080><%= r.count %></font></td>
        <td bgcolor=#88EEDD><font color=#000080><%= r.initial %></font></td>
        <td bgcolor=#88EEDD><font color=#000080><%= r.final %></font></td>
       </tr>
        <% i++; %>
    <% }); %>
<tr align=right>
<td bgcolor=#FFAAFF colspan=2>Total :</td>
<td bgcolor=#FFAAFF><%= total %></td>
</tr>
</table>

Please leave advices or comments, concerning the way I did in the code above, if you happen to read this and be an expert in Node.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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