while using mysql2 with express i got an error :-
Error: Can’t add new command when connection is in closed state
Error: Can’t add new command when connection is in closed state
at Connection._addCommandClosedState (E:SQLCLASSnode_modulesmysql2libconnection.js:164:17)
at Connection.query (E:SQLCLASSnode_modulesmysql2libconnection.js:575:17)
at E:SQLCLASSindex.js:43:20
at Layer.handle [as handle_request] (E:SQLCLASSnode_modulesexpresslibrouterlayer.js:95:5)
at next (E:SQLCLASSnode_modulesexpresslibrouterroute.js:149:13)
at Route.dispatch (E:SQLCLASSnode_modulesexpresslibrouterroute.js:119:3)
at Layer.handle [as handle_request] (E:SQLCLASSnode_modulesexpresslibrouterlayer.js:95:5)
at E:SQLCLASSnode_modulesexpresslibrouterindex.js:284:15
at Function.process_params (E:SQLCLASSnode_modulesexpresslibrouterindex.js:346:12)
at next (E:SQLCLASSnode_modulesexpresslibrouterindex.js:280:10) {
fatal: true
}
// const { faker } = require('@faker-js/faker');
const mysql = require("mysql2");
const express = require('express');
const app = express();
let port = 3000;
// Create the connection to database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'sigma',
password: "Ankit@123",
});
// let getRandomUser = () => {
// return [
// faker.string.uuid(),
// faker.internet.userName(),
// faker.internet.email(),
// faker.internet.password()
// ];
// }
// let q = "insert into user (id,username,email,password) values ?";
// let users = [["123b", "123_newuserb", "newb@gmail", "abcb@123"],
// ["123c", "123_newuserc", "newc@gmail", "abcc@123"]];
// let data = [];
// for (let i = 1; i <= 100; i++) {
// data.push(getRandomUser());
// }
app.get("/",(req,res) =>{
let q = `select count(*) from user`;
try {
connection.query(q,(err, result) => {//here res is an array
if (err) throw err;
console.log(result);
res.send(result);
});
}
catch (err) {
console.log(err);
res.send("some error in db");
}
});
app.listen(port,() =>{
console.log(`server is listening to port ${port}`);
})
connection.end();
// try {
// connection.query(q, [data], (err, res) => {//here res is an array
// if (err) throw err;
// console.log(res);
// console.log(res.length);
// })
// }
// catch (err) {
// console.log(err);
// }
1