I'm trying to create a loop in Node.js with mysql for the Discordbot that waits until the result of the mysql matches what I want, but all I get is this error:
throw err; // Rethrow non-MySQL errors
TypeError: Cannot read property 'day' of undefined
MySql connection and everything else works. But when he didn't find a result, I got this error and my bot crashed.
My Code:
var requestloop = setInterval(function(){
var con = mysql.createConnection({
host: process.env.IP,
user: process.env.US,
password: process.env.PW,
database: "XYZ"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT name,day FROM team WHERE day='0:45'", function (err, result) {
if (err) throw err;
//Sending Congrats
if (result[0].day == "0:45")
{
let Worktime = new MessageEmbed()
.setTitle(result[0].name + `, Congratulations, you've finished work for today`)
.setColor("GREEN");
client.channels.cache.get('702139096683905054').send(Worktime);
con.end();
}
else
{
return con.end();
}
});
});
}, 60000); //1 Minute
if(result? result.day : "0:44" == "0:45")
try this if no result the string will be 44 and just go to else
Related
I would like to know how to pass the value from mysql query to a variable out of the function:
mydb.js
const mysql = require('mysql');
const con = mysql.createConnection({
host: process.env.HOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE
});
con.connect(function(err) {
if (err) throw err;
});
async function loadDataInside(callback){
con.query("SELECT content FROM whatsappauth Where id = 1", function (err, result, fields) {
if (err) throw err;
return callback(result[0].content);
});
}
let ff;
loadDataInside(async function(res){
ff = await res;
});
console.log('++',ff,'gg');
The result is:
++ undefined gg
Why inside the function 'ff' have the right value and out it become 'undefined' ? How should I solve this problem?
Because this is how it execute
let ff;
console.log('++',ff,'gg'); So here you are getting undefined
loadDataInside(async function(res){
ff = await res;
});
You will have to write the code inside the callback function, Or it is better to use promise, Please do not mix the promise and callback.
i want to update result prediction to database mysql, but data cannot save at database.
const periode = _.get(row, "periode", new Date());
const prediction =
b0 +
b1 * Number.parseFloat(_.get(row, "x1", 0)) +
b2 * Number.parseFloat(_.get(row, "x2", 0));
const sql = `UPDATE performance SET prediction_result="${prediction}" WHERE periode="${periode}"`;
db.query(sql, (error, results, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}
})
i am getting error like this:
throw err; // Rethrow non-MySQL errors
ReferenceError: connection is not defined
Can you help me solve this problem?
You should have something like this in your code.
var mysql = require('mysql');
var db= mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Basically, node.js will run the function perfectly, and it will continue running for ~10 seconds and then it will simply crash. Below is the full code, because I dont know what part is causing the actual error, but I hope someone will see where i'm messing up.
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
var fs = require('fs');
var mysql = require('mysql');
const path = require('path');
client.on("ready", () => {
console.log('Running...');
});
var con = mysql.createConnection({
host: "",
user: "",
password: "",
database: "",
});
client.on("message", async message => {
if (message.author.bot) return;
if (!message.guild) {
message.reply('Please do not DM the bot.');
return;
};
if (message.content.toLowerCase() == "!script") {
if (message.channel.name != "bot-chat") {
message.author.send('Please only use bot commands in the #bot-chat channel.');
return;
};
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM Users", function (err, result, fields){
if (err) throw err;
result.forEach(function(User){
var UserDiscord = User.DISCORD;
var UserKey = User.SKEY;
if (usr_dc == message.author.username+"#"+message.author.discriminator) {
message.author.sendCode("php",usr_key)
.then()
.catch(console.log);
if (message.guild.name == "Towlie Boi") {
message.author.sendCode("lua",`_G.key='KeyHere'
loadstring(game:HttpGet("https://basehosting.xyz/sCrIpT1"))()`)
.then()
.catch(console.log);
message.channel.send('Script has been sent to your DMs, If you did not receive a DM then you have not allowed the bot to send you DMs');
.then()
.catch(console.log);
};
};
});
});
});
} else if (message.channel.name == 'whitelist') {
if (message.content.substring(0,3).toLowerCase() == '!wl') {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM Keys", function(err, result, fields) {
if (err) throw err;
result.forEach(function(Key) {
var key = Key.Code;
if (message.content.substring(4) == key) {
var query = "DELETE FROM `Keys` WHERE `Keys`.`Code` = \'"+message.content.substring(4)+"\'";
con.query(query, function(err) {
if (err) throw err;
con.query("INSERT INTO `Users` (`DISCORD`, `SKEY`, `IP`) VALUES ('"+message.author.username+"#"+message.author.discriminator+"', '"+message.content.substring(4)+"', '');", function(err) {
if (err) throw err;
message.reply('Whitelisted Succesfully');
return;
});
});
};
});
});
});
};
};
};
client.login(config.token);
I cant really see a error, as i've just begun coding for node.js and dont know much about javascript, I thought I maybe had to close the connection after I queued the data, but that didnt seem to work either. Thanks for any answers :)
How about connecting database connection from a separate file.
module.exports = {
host : 'localhost',
user : 'root',
password : '',
database : 'bookstore',
charset : 'utf8'
}
and passing on controlling.
var database = require('../models/database.js')();
I have a very basic scenario, I am making a create operation call to MySQL in my NodeJS application. Once I get result of create operation (success or failure) I have to execute some code.
But now due to asynchronous behavior of NodeJS my code which is dependent on result MySQL create operation is getting executed before MySQL create operation sends results back.
Here is my code
calculation.js
var mysql = require("mysql");
var methods = {};
// Creating connection
methods.executeQuery = function(selectQuery, values){
var result;
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "*********",
database: "******"
});
// getting connection
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query(selectQuery, values, function(err,rows){
if(err) throw err;
console.log(rows);
result = rows;
console.log(result);
return result;
});
}
module.exports = methods;
client.js
var execute = require("./calculate.js");
var selectQuery = 'INSERT INTO users (username,password) VALUES (?,?)';
var values = ['sohamsoham12','sohamsoham12'];
var insertedRowInfo = execute.executeQuery(selectQuery, values);
if(insertedRowInfo){
console.log("true");
}else{
console.log("false");
}
I don't know if I correctly understand your question (what is the "create operation", for example?). But...
You can try this solution: execute the query inside the connect success callback:
// getting connection and executing query
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
con.query(selectQuery, values, function(err,rows){
if(err) throw err;
console.log(rows);
result = rows;
console.log(result);
return result; // this can't work... you should invoke a callback function, here...
});
});
UPDATE:
After OP comment, I now fully understand the question... (sorry :-().
You just miss a bit of async behavior... :-)
You should simply change methods.executeQuery from
function(selectQuery, values) {
...
}
to
function(selectQuery, values, callback) {
...
}
Then, instead using
return result;
You should simply use
callback(err, result); // if any error occurred
or
callback(null, result); // if no error occurred
Then, in client.js, when calling the executeQuery method, instead of
var insertedRowInfo = execute.executeQuery(selectQuery, values);
You should simply do
execute.executeQuery(selectQuery, values, function(err, insertedRowInfo) {
if (err) {
// handle error
} else {
// handle success, using insertedRowInfo...
}
});
code as follows:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port :"3306",
database :"mydb",
user : 'root',
password : '007007',
});
var isCon = true;
connection.connect(
function (err) {
console.log(isCon);
if (err) {
isCon=false;
console.error("error connecting :"+err);
return;
};
}
);
if(isCon){
connection.query('select * from tb_items', function(err, result) {
if (err) throw err;
console.log('The solution is: ', result);
console.log('The typeof solution is ',typeof(result));
debugger;
});
connection.end();
}
connection.connect(
function (err) {
console.log(isCon);
if (err) {
isCon=false;
console.error("error connecting :"+err);
return;
};
}
);
if(isCon){
connection.query('select * from tb_items', function(err, result) {
if (err) throw err;
console.log('The solution is: ', result);
console.log('The typeof solution is ',typeof(result));
debugger;
});
connection.end();
}
i just open()-->connect()-->query()-->end(),then did it again,but second time , there is a error : Error:Could not enqueue Handshake after invoking quiting .
question : maybe i can't reopen it after end().but i just wanna kwon ,if i end(),how can i reopen it?
no, you can't, just create another one. All state in the connection class only relevant for current connection, so having "reopenWithSameConfig" method is possible, but you should really do this from outside.
Also, you don't need to close connection on each query - just continue to reuse it without calling .end()
If you want multiple connections and automatic disposal of dead connections you should use Pool class.
One more note: your isCon check is incorrect, connection.query is called before connect() callback so it's always true. It's safe to just check error in query callback itself. If connection was not successful error is propagated to a queued command