Check if MySQL row exists - Node.JS - javascript

Previous post I will refer to later
I am making a Discord bot which uses MySQL, but that shouldn't matter, I am trying to do a blacklist database so users in it can't use my bot
This is what I got so far:
con.query("SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')", function(error, result, field) {
if(error) throw error;
});
And this kinda works, this is my output
[ RowDataPacket {
'EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = \'227090776172134400\')': 1 } ]
And the last digit works like a boolean, 1 if the row exists, 0 if it does not
But my problem is, that I can't seem to figure out how to check if it's a zero or not because it's an object

Why can't you make the query string a variable that you can later query on. For example:
let conStr = "SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')";
con.query(conStr, function(error, result, field) {
if(error) throw error;
console.log(result[conStr]); //--> 1
});

Related

how to insert array of data per column in MySQL?

I have arrays stacked in 1 array and I would like to insert each array per column in MySQL.
I have reached to insert all data in arrays to 1 column, but I want to insert an array per column.
Please see the screenshot and code below.
Image of array stack
con.connect(async(err)=>{
const x = await getStock()
if(err){
console.log(err);
return err;
}else{
console.log("DB ok");
}
console.log("connected");
x.filter(item=>item===undefined?false:true).map(item=>item.forEach(item=>{
const sql ="INSERT INTO test (testCol1) VALUES ?";
const values=[
[item]
];
con.query(sql,[values],(err,result)=>{
if(err)throw err;
console.log("this have been recorded"+result);
});
}));
});
I just found a solution for this case.
It can be a little bit confusing but it is working.
Maybe there exists way easier and understandable solution, but this is the solution I have at the moment.
In the code above I was using only 1 array iterator, which was returning me an array. I decided to iterate the returned array to get each integer and insert data into MySQL, also the (test${i+1}) sets array into necessary column.
x.filter(item=>item===undefined?false:true).forEach((item,i)=>{
item.forEach(item=>{
const sql =`INSERT INTO test (test${i+1}) VALUES ?`;
const values=[
[item]
];
con.query(sql,[values],(err,result)=>{
if(err)throw err;
console.log("this have been recorded"+result);
});
})
});

How to save information from an SQL query to a variable

I'm trying to save the information I get from my inmatefirst column with my SQL query into the variable "first'. I was wondering what the correct syntax/approach was to doing this.
let sql = `SELECT * FROM inmates WHERE inmatefirst = ? AND inmatelast = ? AND dob = ?`;
let query = db.query(sql, [search.first, search.last, search.dob], (err, result) => {
if (err) throw err;
if (result.length != 0) {
res.render(path.resolve('./myviews/modify'), {
good: 'Person Found - Please Enter Updated Information',
first: result.inmatefirst,
last: result.last,
dob: result.dob,
sex: result.sex
});
});
});
Your SQL says, in part, this:
SELECT * FROM inmates WHERE inma...
You've asked for every column from the table. That can make life confusing.
Instead, spell out the columns you want. Your Javascript indicates that you want these ones:
SELECT inmatefirst, last, dob, sex FROM inmates WHERE inma...
(It's possible that is the wrong set of columns. Check it.
Then, as #barmar pointed out, use result[0].first etc, because result is an array of objects, one for each row of your resultset.

How to avoid duplicated random id selection in MySQL?

I need to select two unique random id from table nodes and insert it in parent column in edges table.
But problem is that they are sometimes duplicated and it need them to be always different, how could I avoid that, please?
the code:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'DAGtest3'
});
connection.connect((err) => {
if (err) throw err;
console.log('Database Connected!');
});
var a = "INSERT INTO `edges` (`parent`, `child`) VALUES ((SELECT `id` FROM `nodes` ORDER BY rand() LIMIT 1 ) , (4) )";
connection.query(a, (err, res) => {
if(err) throw err;
console.log("1 edge inserted to previous data");
});
var b = "INSERT INTO `edges` (`parent`, `child`) VALUES ((SELECT `id` FROM `nodes` ORDER BY rand() LIMIT 1) , (4) )";
connection.query(b, (err, res) => {
if(err) throw err;
console.log("Another edge inserted to previous data");
});
code for the tables:
CREATE TABLE nodes (
id INTEGER NOT NULL AUTO_INCREMENT,
sensorvalue VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
CREATE TABLE edges (
parent INTEGER NOT NULL REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE,
child INTEGER NOT NULL REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE,
PRIMARY KEY (parent, child)
);
CREATE INDEX parent_idx ON edges (parent);
CREATE INDEX child_idx ON edges (child);
Thanks in advance.
You don't want two sequential random selections, since there's a non-zero chance that the second random selection could return the same row as the first. I think you should just fetch both rows at once:
INSERT INTO `edges` (`parent`, `child`) SELECT `id`, 4 FROM `nodes` ORDER BY rand() LIMIT 2;
So, your code would just have one query to execute, instead of two:
var a = "INSERT INTO `edges` (`parent`, `child`) SELECT `id`, 4 FROM `nodes` ORDER BY rand() LIMIT 2";
connection.query(a, (err, res) => {
if(err) throw err;
console.log("2 edges inserted to previous data");
});
When I set up your DB locally and run the above code, I get a successful insert:
Database Connected!
2 edges inserted to previous data
When I query the DB in the console I get:
mysql> select * from edges;
+--------+-------+
| parent | child |
+--------+-------+
| 2 | 4 |
| 3 | 4 |
+--------+-------+
2 rows in set (0.00 sec)

what the best way to insert a relationship table in mysql using NodeJS

First of all I have to say I'm totally newbi in NodeJS technologies.
But, I've tried to do something to try to learn it.
This is the problem:
I have 3 tables (PARTICIPANT, ADDRESS_PARTICIPANT and INSCRIPTION).
The ADDRESS_PARTICIPANT contains participant_id (it's the participant's address).
The INSCRIPTION contains participant_id
So, to store a inscription row, at first I need to save the PARTICIPANT and the ADDRESS_PARTICIPANT. Only after this I could insert INSCRIPTION
I'm doing this in the way i've learn, but I think there are a lot of nested ifs.
How could I improve this code? Someone told me with Promise i'll well.. but I don't know. Someone could help me? Thanks
Here is the code:
this.save = function(data, retur) {
var con = db();
const SQL_INSERT_PARTICIPANT =
`INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( ? )` ;
const SQL_INSERT_ADDRESS_PARTICIPANT =
`INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( ? )`;
const SQL_INSERT_INSCRIPTIONS = `......`
var values = [
data.nome_completo, data.tipo_funcionario, new Date(dateToEN(data.data_nascimento)), data.sexo, data.unidade, data.cpf_funcionario, data.email, data.telefone, data.telefone_emergencia
]
const insertParticipante = con.query(SQL_INSERT_PARTICIPANT , [values], function (err, result) {
if (err) throw err;
var values_end = [
result.insertId, data.cep, data.estado, data.cidade, data.bairro, data.endereco, data.numero
]
if (result.affectedRows > 0 ) {
const insertEndPart = con.query(SQL_INSERT_ADDRESS_PARTICIPANT , [values_end], function(err, result2 ) {
if (err) throw err;
console.log('Number of records inserted in ADDRESS_PARTICIPANT table: ' + result2.affectedRows);
console.log('insertId.: ' + result2.insertId)
if (result.affectedRows > 0 ) {
const insertInscricao = con.query(SQL_INSERT_INSCRIPTIONS, [values_ins], function(err, result3) {
console.log(`Inscription recorded! id: `+resul3.insertId)
})
}
})
}
})
}
You can use MySQL's LAST_INSERT_ID i assume every table has a primray key column with a auto_increment option.
With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit)
value representing the first automatically generated value
successfully inserted for an AUTO_INCREMENT column as a result of the
most recently executed INSERT statement. The value of LAST_INSERT_ID()
remains unchanged if no rows are successfully inserted.
https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id
Then you can use these INSERT's in NodeJS instead.
INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( <other columns> )
This insert below will use LAST_INSERT_ID() to get the participant.id
INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( LAST_INSERT_ID(), <other columns> )
With three table the problem gets more complex.
Then you can use MySQL's user variables.
INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( <other columns> )
SET #participant_id = LAST_INSERT_ID();
INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( #participant_id, <other columns> )
SET #endereco_participante_id = LAST_INSERT_ID();
Then you can use #participant_id and #endereco_participante_id in the third insert query. (which seams you didn't provided in your question).
Note the SET queries are separated queries so you need to execute them also with con.query('SET #participant_id = LAST_INSERT_ID();', ..)

Best Approach to a 3 Table Update for Tagging System in NodeJS and MySQL

I'm writing an application that let's a user post content (called "moments") along with one or more tags associated with that content.
I have a 3 table data model (in MySQL) that looks like this:
Table: MOMENTS, Columns: MOMENT_ID, USER_ID, TITLE, CREATE_DATE
Table: TAGS, Columns: TAG_ID, TITLE, CREATE_DATE
Table: MOMENTS_TAGS, Columns: MOMENT_ID, TAG_ID
Auto-Increment is set for: MOMENT_ID and TAG_ID
The problem I'm trying to solve (in NodeJS) is: how do I insert a new post (in MOMENT table) and 1 or more tags (in TAGS table), get their respective ID's and do a 3rd insert into the junction table (MOMENT_TAGS)?
I've already attempted to solve this (using mysqljs) by doing 3 successive queries, first MOMENTS, then TAGS, then MOMENTS_TAGS, but it fails because although the first result1.insertId returns the correct number, the 2nd result2.insertId doesn't seem to return the correct number from the TAGS table and instead simply increments the first result1.insertId.
Here is my code so far (I'm trying to get this to work for 1 tag at first):
app.post('/api/post/complex', function(req,res) {
pool.getConnection(function(err, connection) {
var preppedQuery1 = "INSERT INTO MOMENTS (USER_ID, TITLE, CREATE_DATE) VALUES ('justatest#gmail.com','test moment title','2016-08-08')";
connection.query(preppedQuery1, function(err1, result1) {
if (err1) {
res.send('ERROR');
connection.release();
}
else {
var preppedQuery2 = "INSERT INTO TAGS (TITLE, CREATE_DATE,USER_ID) VALUES ('TEST TAG', '2016-09-08','justatest#gmail.com')";
connection.query(preppedQuery1, function(err2, result2) {
if (err2) {
res.send('ERROR');
connection.release();
}
else {
var preppedQuery3 = "INSERT INTO MOMENTS_TAGS (MOMENT_ID, TAG_ID) VALUES (" + result1.insertId + "," + result2.insertId + ")";
//At this point if result.insertId is 100, result2.insertId is always 101 instead of coming from the TAGS table
//Why isn't result2.insertId the auto-incremented number from the TAGS table insert?
connection.query(preppedQuery3, function(err3, result3) {
if (err3) {
res.send('ERROR');
connection.release();
}
else {
console.log(result3); //not really needed
res.send('OK'); //everything worked
connection.release();
}
});
}
});
}
});
});
});
It looks like you're running preppedQuery1 twice.
Typo here:
(Assuming that's not just a typo in the post and actually exists in your source...)
Resolved: typo in 2nd preppedQuery (used 1 again, instead of 2).
Tested things and correct insertId is being assigned.

Categories