0

I`m trying to create a database with mysql module in nodejs but after I create a table and insert some data, when I try to SELECT and get results back, I face fatal error!!

    D:\Programming\Farahani App\App>node mysql.js
    Error: Cannot enqueue Query after fatal error.
        at Protocol._validateEnqueue (D:\Programming\Farahani App\App\node_modules\mysql\lib\protocol\Protocol.js:212:16)
        at Protocol._enqueue (D:\Programming\Farahani App\App\node_modules\mysql\lib\protocol\Protocol.js:138:13)
        at Connection.query (D:\Programming\Farahani App\App\node_modules\mysql\lib\Connection.js:198:25)
        at Handshake.<anonymous> (D:\Programming\Farahani App\App\mysql.js:28:13)
        at Handshake.<anonymous> (D:\Programming\Farahani App\App\node_modules\mysql\lib\Connection.js:526:10)
        at Handshake._callback (D:\Programming\Farahani App\App\node_modules\mysql\lib\Connection.js:488:16)
        at Handshake.Sequence.end (D:\Programming\Farahani App\App\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
        at Protocol.handleNetworkError (D:\Programming\Farahani App\App\node_modules\mysql\lib\protocol\Protocol.js:369:14)
        at Connection._handleNetworkError (D:\Programming\Farahani App\App\node_modules\mysql\lib\Connection.js:418:18)
        at Socket.emit (node:events:390:28) {
      code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR',
      fatal: false
    }
    undefined

[mysql is running in my xampp if related... ]

appreciate your help.

my code:

const mysql = require('mysql');

const data = {
    host: "localhost",
    user: "user",
    password: "password",
    database: "mydb"
}
const con = mysql.createConnection(data)

    con.connect(() => {


        // create database 
        con.query('CREATE DATABASE mydb', () => {

        })
        // create table
        const table = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
        con.query(table, () => {
            })
        // add val to table
        const val1 = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
        con.query(val1, () => {

        })
        // log results
        con.query("SELECT * FROM customers",  (err,result)=>{
            if(err) {console.log(err)};
            console.log(result);
        })
        con.end();
    })
4
  • as con.query is async, but you are not awaiting the query results, you are executing multiple queries in parallel. Especially, you are not awaiting the creation of your database before creating your customers table. And you are not awaitng the creation of your table before inserting and reading from it. Commented Jan 7, 2022 at 22:15
  • And probably, after creating a new database, you will need to update the scope of your connection to this database. Commented Jan 7, 2022 at 22:38
  • derpirscher, OP is using callback chains to handle async. The formatting is a little off so it's hard to see. ali-babaee, you may want to convert your code to use promises and async / await to make things easier to understand. Commented Jan 7, 2022 at 23:40
  • @kevintechie Yes, he is using callbacks. But still, all the con.query("..", () => {}) are on the same nesting level. Ie, executing the CREATE TABLE query doesn't happen within the callback of CREATE DATABASE but outside of it. Thus, this piece of code won't wait for the callback to be executed before executing the next con.query(...). All con.query() are nested in the callback of con.connect() though ... The formatting is perfectly fine and exactly fitting to the nesting levels. Commented Jan 8, 2022 at 11:51

2 Answers 2

2

There are two problems with your code. The main problem is that you cannot do multiple queries per connection in mysql.

You can use connection pools to make this easier to manage.

Second, you should check for errors in the callback. This will help in debugging as well as making your code more robust.

con.query("select * from my_table", (error, results, fields) => {
  if (error) throw error;
  console.log(results);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks sir for your points. the things is I dont know where to use await in con.query() because I dont see any callbacks but consol.log(err). and after using pool connections I`m facing the ACCESS_DENIED_ERROR.
I wasnt allowed to share my code as a comment so I put it as a new answer if you may check below....>>>
0
const mysql = require('mysql');

const con  = mysql.createPool({
    host: "localhost",
    user: "user",
    password: "password",
    database: "mydb"
});

        // create database 
        con.query('CREATE DATABASE mydb', (err) => {
            if(err) {console.log(err)};
        })
        // create table
        const table = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
        con.query(table, (err) => {
            if(err) {console.log(err)};
            })
        // add val to table
        const val1 = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
        con.query(val1, (err) => {
            if(err) {console.log(err)};
        })
        // log results
        con.query("SELECT * FROM customers",  (err,result)=>{
            if(err) {console.log(err)};
            console.log(result);
        })
    

2 Comments

If you update your code, you shouldn't create an answer but edit your question with the new code (and probably some remarks on what you changed ...)
You should place questions updates inside the question itself by using the edit button underneath your question

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.