I am little new in JavaScript so i need to ask cause is different from Java..
I have an application and when starts i connected with mysql2 with this function:
connection.js
const mysql = require('mysql2');
const con = mysql.createConnection({
host: "127.0.0.1",
user: "user",
password: "passwd",
database: "db"
});
con.connect(function (err) {
if (err) throw err;
if (err !== null) {
console.log(err);
}
});
module.exports = {con};
I have export the ‘con’ so i can use it in some other files and works ok.
So the question is:
let sql = "insert into reports(someValues) values (?)";
try {
e.con.execute(sql, [someValues], function (err, result) {
if (err) throw err;
});
} catch (err) {
console.error(err);
}
when this query will be executed i want if is necessary to close the specific query.
Is it important to close this query or i can leave it as is because i execute multiply query’s and i didn’t find any way to close it…
Does anyone have any idea how to close the query after executed or i need to close the connection and reconnect after in the other query?
Thanks in advance!
Edit: i connect with const con = require("./connection");
2
Answers
You could create a wrapper class that keeps a handle on the client connection.
This class acts as an interface and encapsulates the
mysql2
logic. If you wanted to changemysql2
out for another module, you would not have to change all the usages of this class across your codebase.Update
Here is an example of Evert’s suggestion of
mysql2
.Dependencies
Sample SQL
Based on: https://www.w3resource.com/sql/sql-table.php
Environment
Usage
Here is an example of creating reusable query functions:
After you (or someone) call API on frontend and query will be executed.
So about you question you can close, or finish request on few ways.
First you can add this:
And when you send results on frontend query and API call is closed and finished.
Or you can use
res.end();
method.I hope my answer will help you.