I am trying to Skip the data if there is nothing return from the mySql Database How can I achieve it?
Here is my code
const mysql = require('mysql2');
function dbconnection() {
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
database: 'DB'
});
var Data_export = dbconnection();
Data_export.query(sql, function (err, data, fields) {
if (err) throw err;
if (data !== Null) {
const jsonData = JSON.parse(JSON.stringify(data));
fastcsv
.write(jsonData, { headers: true })
.on("finish", function () {
console.log("Write to file.csv successfully!");
})
.pipe(ws);
} else { console.log("Nothing"); }
But it doesn't work Any help would be greatly appreciated, thanks!
CodePudding user response:
You must return something on your connection's function, and the code has some syntax issues.
It must work:
function dbconnection() {
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
database: 'DB'
});
return connection;
}
var Data_export = dbconnection();
Data_export.query(sql, function (err, data, fields) {
if (err) throw err;
if (data !== Null) {
const jsonData = JSON.parse(JSON.stringify(data));
fastcsv
.write(jsonData, { headers: true })
.on("finish", function () {
console.log("Write to file.csv successfully!");
})
.pipe(ws);
} else {
console.log("Nothing");
}
});
CodePudding user response:
I found the solution
Because it is a return array from the mysql, So instead of
if (data !== Null) {
const jsonData = JSON.parse(JSON.stringify(data));
fastcsv
.write(jsonData, { headers: true })
.on("finish", function () {
console.log("Write to file.csv successfully!");
})
.pipe(ws);}
I use this one
if (data.length !==0) {
const jsonData = JSON.parse(JSON.stringify(data));
//write duplication to CSV file
fastcsv
.write(jsonData, { headers: true })
.on("finish", function () {
console.log("Write to file.csv successfully!");
})
.pipe(was); }