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!
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");
}
});
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); }
Related
I have:
const connection = mysql.createConnection({
host: process.env.APP_DATABASE_HOST,
user: process.env.APP_DATABASE_USER,
password: process.env.APP_DATABASE_PASS,
database: process.env.APP_DATABASE_NAME,
port: process.env.APP_DATABASE_PORT
});
const connectDataBase = () => {
connection.connect(function(error){
if(error){
console.log(error);
}else{
console.log('Connected');
}
});
}
exports.search = async (id) => {
try {
connectDataBase();
await connection.query(`SELECT * from devices where numberserial="${id}"`, function (err, result, fields) {
if( result ){
return true;
}
return false;
});
closeConnectionDataBase();
} catch (error) {
console.log(error)
}
};
const closeConnectionDataBase = () => {
connection.end();
}
I want that when it gets the element it returns true, but if it doesn't get the element it returns false.
for now if it gets the element it returns true, the problem I'm having is when it doesn't get the element the terminal gets stuck, what am I doing wrong??? what I want is that if the element is not found in the database it returns false
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "anujsingh",
database: "test",
});
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
const selectCountries = async () => {
let sql = "SELECT countries.* FROM countries";
try {
let result = await con.query(sql);
console.log(result);
} catch (err) {
console.log(err);
}
};
selectCountries();
Attached screenshot of console, I am not getting what exactly I am getting, I want to call a function where I am consoling and send that data to a function which make insert queries based on that data.
You can not use con.query in such a way as it returns a function with more than just results. You also do not need to call con.connect() - it is implicit with every .query()
The following should work for you. I've included additional functions to illustrate the async nature of the approach.
var mysql = require('mysql');
var connection = mysql.createConnection({
host: process.env.HOST || '127.0.0.1',
user: process.env.USER || 'local_user',
password: process.env.PASSWORD || 'local_password',
database: process.env.NAME || 'local_database'
});
const do_thing_one = async (payload) => {
return new Promise((resolve, reject) => {
payload.one = 'thing one';
resolve(payload)
});
};
const selectCountries = async (payload) => {
return new Promise((resolve, reject) => {
connection.query('SELECT countries.* FROM countries', function (error, results, fields) {
if (error) reject(error);
payload.countries = results
resolve(payload);
});
});
};
const do_thing_three = async (payload) => {
return new Promise((resolve, reject) => {
payload.three = 'thing three'
resolve(payload)
});
};
const execute = async () => {
let payload = {}
await do_thing_one(payload)
await selectCountries(payload)
await do_thing_three(payload)
console.log(payload);
}
execute();
Will log…
{
one: 'thing one',
countries: [
RowDataPacket { id: 1, name: 'Brazil' },
RowDataPacket { id: 2, name: 'China' },
RowDataPacket { id: 3, name: 'Japan' }
],
three: 'thing three'
}
I'm new to Node.js I'm testing some code on Wix to check my database if a account name already exists prior to allowing a new one to be created (I'm purposely not using the WHERE tag at the moment for learning purposes).
Currently the method check account name returns before the connection finishes, not allowing the check to take place properly.
Any help appreciated.
export function tryToCreateAccount(login, password)
{
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
if(checkAccountName(login, connection))
{
console.log("Name didn't exist.");
}
else
{
console.log("Name Existed.");
}
}
function checkAccountName(account_name, connection)
{
var accountNameAvailable = true;
connection.connect(function (err)
{
if(err) throw err;
connection.query("SELECT login FROM accounts", function (err, result)
{
if (err) throw err;
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == account_name)
{
console.log("Should of been false");
connection.end;
accountNameAvailable = false;
}
}
});
connection.end;
});
return accountNameAvailable;
}
I figured out why it wasn't doing anything, the next was getting called too late since the connection ended and next was within the connection code block.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
export function tryToCreateAccount(login, password)
{
checkAccountName(login, connection, function(err, accountNameAvailable)
{
if(err || !accountNameAvailable){
console.log("Name didn't exist.");
}
else
{
console.log("Name Existed.");
}
})
}
function checkAccountName(login, connection, next)
{
var accountNameAvailable = false;
connection.connect(function (err)
{
if(err) next(err);
connection.query("SELECT login FROM accounts", function (err, result){
if (err) next(err);
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == login)
{
accountNameAvailable = true;
}
}
next(null, accountNameAvailable);
connection.end();
});
});
}
Welcome to Node.js (and the world of Async functions (and Promises (and Callbacks)))
I've written this in the "callback" style, but I highly recommend looking into async/await for something like this, as well as understanding how "promises" fit into the picture.
// to test, call tryToCreateAccount('login','pass',function(err,data){console.log(err,data)});
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
export function tryToCreateAccount(login, password, next)
{
checkAccountName(login, connection, function(err, accountNameAvailable){
if(err || !accountNameAvailable){
console.log("Name didn't exist.");
next(err || 'Name didn't exist.')
}
else
{
console.log("Name Existed.");
next(null, true)
}
})
}
function checkAccountName(account_name, connection, next)
{
var accountNameAvailable = false;
connection.connect(function (err)
{
if(err) next(err);
connection.query("SELECT login FROM accounts", function (err, result){
if (err) next(err);
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == account_name)
{
console.log("Should of been false");
connection.end;
accountNameAvailable = true;
}
}
connection.end();
next(null, accountNameAvailable);
});
});
}
I made this:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
console.log(query('SELECT * FROM `users`'))
and I got back
Promise { <pending> }
How do I get back my results from querying the database, just like PHP can do?
In PHP I never had to do such a thing like async/await and promises...
I also tried using mysql:
const mysql = require('mysql')
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs'
})
function query(query) {
db.query(query, (err, result) => {
if (err) throw err
return result
})
}
console.log(query('SELECT * FROM `users`'))
but I got an undefined result
try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
// function definition
function runQuery (con, sqlQuery) {
return new Promise((resolve, reject) => {
console.log("START");
if(con){
con.connect(function (err) {
if (err) throw err;
});
if (sqlQuery) {
con.query(sqlQuery, function (error, result, fields) {
connection.end(); // end connection
if (error) {
throw error;
} else {
return resolve(result);
}
});
} else {
connection.end(); // end connection
// code: handle the case
}
} else {
// code: handle the case
}
});
}
var sqlQuery = 'SELECT * FROM tableName';
// function call and pass the connection and sql query you want to execute
var p = runQuery(con, sqlQuery);
p.then((data)=>{ // promise and callback function
console.log('data :', data); // result
console.log("END");
});
I am not very familiar with MySQL and the libraries that you are using.
However, the Promise { <pending> } response that you are getting is because you didn't await your query execution.
Since the function is marked as async and is also performing an async action, it returns a Promise that needs to be awaited to be resolved.
The code below should work:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
(async () => {
const queryResult = await query('SELECT * FROM `users`');
console.log(queryResult);
} )();
To understand how async-await works, consider the code below:
console.log('I will get printed first');
const asyncFunction = async () => {
await setTimeout(()=> {}, 1000)
console.log('I will get printed third');
return 'hello'
}
(async () => {
const result = await asyncFunction();
console.log(`I will get printed last with result: ${result}`);
})();
console.log('I will get printed second');
The console.log statement I will get printed last with result will wait for the asyncFunction to complete execution before getting executed.
Try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Hi i want to use Mysql's beginTransactio or transactio commit rollback functionality in my Lambda(Node) function.
I tried basic structure of mysql package but seems its not working in lambda
const mysql = require('mysql');
exports.handler = async (event) => {
const con = mysql.createConnection(
{
host: "host",
user: "user",
password: "*****",
database: "db"
}
);
con.beginTransaction(
function (err) {
con.query(
"query goes here",
function (err, status) {
if (err) {
con.rollback();
con.end();
return err;
} else {
con.commit();
con.end();
return true;
}
})
});
}
sorry for the delayed answer.
just needed to specify beginTransaction without callback
const mysql = require('mysql');
exports.handler = async (event) => {
const con = mysql.createConnection(
{
host: "host",
user: "user",
password: "*****",
database: "db"
}
);
con.beginTransaction(); //here i was declaring standard callback function with err parameter
con.query(
"query goes here",
function (err, status) {
if (err) {
con.rollback();
con.end();
return err;
} else {
con.commit();
con.end();
return true;
}
});
}