How can I update data using NodeJS? - mysql

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!");
});

Related

Cannot enqueue Handshake after already enqueuing a Handshake

const app = require('./app');
var mysql = require('mysql');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
I learning nodejs 3 day but i don't know how can i fix it i try to fix it but not work.
Someone Help me please
I don't know what i wrong. I want to insert data into mysql with pug
be like login with html and use php to select data in phpmyadmin
register in pug and data send to nodejs and node post data to mysql
I'm sorry my English and gramma so bad :(
const express = require('express');
var mysql = require('mysql');
const router = express.Router();
const app = require('../app.js');
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database:"project_test"
});
conn.connect(function(err) {
if (err) throw err;
console.log("Index Connection!");
});
conn.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customer (name, address) VALUES ('Company Inc', 'Highway 37')";
conn.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
module.exports = router;

Node.JS MySql Waiting for expected result in Loop

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

How to fix "err is not defined" error in Nodejs

I'm trying to establish a connection to mysql database in Nodejs but it won't compile as "err is undefined". I'm fairly new to Node.js, but I thought this was the appropriate way to handle errors, even with the mysql package, which is the only difference from my other projects where I did not encounter this issue.
throw err; // Rethrow non-MySQL errors
^
ReferenceError: err is not defined
const express = require('express');
const mysql = require('mysql');
//Create connection
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'ca1903'
});
//Connect
db.connect(() => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});
const app = express();
//create DB
app.get('/createdb', () => {
let sql = 'CREATE DATABASE ca1903';
db.query(sql, (err, result) => {
if(err){
console.log(err);
}
console.log(result);
res.send('database created....');
});
});
You were missing err parameter in the db.connect call. It should be in the below way.
// Connect
db.connect((err) => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});

Looping through JSON file and inserting into mysql database table using node.js

I have a number of values in a JSON file set out as follows:
[{"scraped_at": 1533384162.2934802, "server_id": "461235834994032661", "invite_code": "5uWt6B", "server_name": "Magic Pokemon", "members": ["115385224119975941", "133557837598031872"]}
As can be seen the last value is another array. I've been trying to use the following code to insert into the mysql database using node.js:
const fs = require('fs');
var obj;
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "list"
});
fs.readFile('list.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
for(var i = 0; i < obj.length; i++) {
const s_at = obj[i].scraped_at;
const s_id = obj[i].server_id;
const s_inv = obj[i].invite_code;
const s_sn = obj[i].server_name;
const mbs = obj[i].members;
const sql = 'INSERT INTO members (scraped_at, server_id, invite_code, server_name, servermbs) VALUES ('+s_at+','+s_id+','+s_inv+','+s_sn+','+mbs+')';
con.query(sql, function (err, result) {
if (err) throw err;
console.log("x record inserted");
});
}
});
});
I'm currently getting the following error thrown:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RP,115385224119975941,133557837598031872,160105994217586689,212681528730189824,2' at line 1
Anyone got any ideas what is up with it and if so any solutions?
Apologies if the code doesn't look too great as I've never been good at formatting on this community site.
Thanks!

Validation in express Rest Apis

I am saving signup value into database using expressjs in Rest api but how can i valuate my fields (name,email,password) so if i save without data then error message related to field should show
Here is my code
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
var toTime = new Date();
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO users (name, email,password) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.password+"')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
First note: you're code is susceptible to SQL injection. Refer: this SO question
Now, You can just make a validation function which returns booleanand use it before the query like
function validateFunc(...params){
return params.reduce((p,c)=> p && (c !== null && c !== undefined), true);
}
And use it like,
if(!validateFunc(req.body.name, req.body.email, req.body.password)){
// throw some error
}
var sql = "INSERT INTO users (name, email,password) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.password+"')";