-2

Despite having correct server credentials this segment of code being called from a function never reaches the alert at the bottom of the snippet nor does it provide any error message despite the inclusion of a throw err statement. It reaches the alert saying "PING" but never even executes the "PONG" alert. What is wrong here? In MySQL Workbench the credentials seem to be correct and I've inserted data into columns using that environment just fine.

    alert("PING");
    //Begin SQL query
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : '127.0.0.1',
      user     : 'root',
      password : 'password',
      port: 3306,
      database : 'db'
    });
    connection.connect();
    connection.query('SELECT * FROM test', function(err, rows, fields) 
    {
      if (err) throw err;
      console.log(rows[0]);
    });
    connection.end();
    alert("PONG");
11
  • There's no alert() function in node? Are you running this in a browser? If so, you'll get an error message for using require. Node JavaScript and browser JavaScript are not the same. Requiring modules like that and accessing a DB directly is only possible with node. Commented Jun 7, 2021 at 22:26
  • How long did wait for an output before killing the process? it maybe that the mysql server for some reason is not send data back and your nodejs process just wait for it Commented Jun 7, 2021 at 22:27
  • @ChrisG Yes there is the first alert executes fine. The second alert never displays and there is no error provided in console. Commented Jun 7, 2021 at 22:28
  • The code works fine for me if I remove the alert statements and run this from the command line using node test.js. If you see an alert displayed, you're running this as <script> in a browser. However mysql is a node module, i.e. backend. Commented Jun 7, 2021 at 22:30
  • how are you calling alert() and require(mysql)? Could you tell us a little more on how are you running this script? Commented Jun 7, 2021 at 22:30

1 Answer 1

1

Pass your .query() section as an argument of the .connect() function like this:

connection.connect(function(err) {
  if err throw err;
  connection.query('SELECT * FROM test', function(err, rows, fields) {
    if (err) throw err;
    console.log(result);
    });
})

That should work better.

Sign up to request clarification or add additional context in comments.

2 Comments

Removing the alert commands makes OP's code run fine.
@ChrisG I just removed all of the alerts and it still doesn't work and it doesn't throw any errors. I am working in a React environment and I'm confused as to what is wrong...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.