Syed Salleh
Syed Salleh

Reputation: 61

Can't add new command when connection is in closed state (express.js + mysql2 + mysql2/promise + clearDB + heruko)

i am facing thi error whenever i make a second call to the api i created using mysql2+expressjs+clearDB(on HERUKO)+heruko deployment server

this is my code ....

const [rows,fields]= await db.execute(MYQUERY,[myarguments])

i am calling the mysql server like this with asyn/await functionality which mysql2 provides

import mysql from 'mysql2/promise'

after that i create the the connection

 let db = await mysql.createconnection({
 host: 'localhost',
 user: "root",
 password: "asdzxcasdzxc123123",
 database: "doctorapp"

}) export { db }

Any sollution to this error...???

Upvotes: 1

Views: 3351

Answers (1)

Syed Salleh
Syed Salleh

Reputation: 61

i was facing this error in mysql2/promise

Reason for this error

The actual problem is with mysql2/promise .

when you create your connection with mysql database with mysql2 npm package this thing is causing the error...

Sollution to this error

i solved this error by creating my connection with mysql.creatPool(yourCredentials)

creat your db config file like this

import mysql from 'mysql2'

let db = mysql.createPool({
host: 'Enter your host here',
user: "enter user name here",
password: "enter you password",
database: "enter the database name",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
export { db }

Use of db in your contollers or router should be like this

 const promise = db.promise()
 const select_user_query=`
 select *
 from users
 `
 const [rows,fields]= await promise.execute(select_user_query)
 return res.status(200).json({users:rows})

One thing to note===>

you have to create

const promise= db.promise()

in all the contollers ... so it will automatically handles all the required connnection release or other things required to make the connection working perfectly

Upvotes: 2

Related Questions