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();
})
con.queryis 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 yourcustomerstable. And you are not awaitng the creation of your table before inserting and reading from it.con.query("..", () => {})are on the same nesting level. Ie, executing theCREATE TABLEquery doesn't happen within the callback ofCREATE DATABASEbut outside of it. Thus, this piece of code won't wait for the callback to be executed before executing the nextcon.query(...). Allcon.query()are nested in the callback ofcon.connect()though ... The formatting is perfectly fine and exactly fitting to the nesting levels.