Insert Value in Mysql via node.js - javascript

I use Node.js and i want to INSERT few value in my table.
like:
id | profile_id | user_id
1 | 2 | 7
2 | 2 | 3
3 | 2 | 4
4 | 2 | 6
i have an array (user_id) with all my date(ids), i have to do a foreach in my array for insert each user_id value like
foreach...
connection.query('INSERT INTO mytable SET ?', my_obj, function(error,risultato) { ...
or i can do a cycle inside mysql with one statement?

You can use the following syntax for multiple insterts in MySQL:
INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?);
Therefore yor code would be:
connection.query("INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?)",
[id1, profile_id1, user_id1, id2, profile_id2, user_id2, id3, profile_id3, user_id3],
function(err, result){ .... });

After answer #Mustafa i do it: (use sugar.js and felixge/node-mysql)
var place ="(";
rows.each(function(n) {
columns.add(n.profile_id);
columns.add(n.user_id);
columns.add(new Date());
place += '(?,?,?),';
});
place= place.slice(0,place.lastIndexOf(","));
var sql = 'INSERT INTO mytable (profile_id,user_id,created) VALUES '+place+' ON DUPLICATE KEY UPDATE id=id';
connection.query(sql,
columns
, function(error, rows) {
if (error) {
var err = "Error on " + error;
console.dir(err);
console.log('>>>>>ERROR<<<<< ' + err);
throw err;
}
connection.release();
callback(rows);
I hope to help someone

Related

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();', ..)

insert statement in nodejs for loop?

I am trying to insert multiple values into the nosql database cassandra, using an array, but when I use the code below, instead of adding a row for each of the values stored in foo5 it only ends up adding two rows. The two rows added contain the same value in col5 and col3
var insert2 = "INSERT INTO content (col, col2, col3, col4, col5) VALUES (?, ?, ?, ?, ?);"
for(var i = 0; i < foo5.length; i++) {
client.execute(insert2, [foo, foo2, foo3, foo4, foo5[i]], {prepare : true}, function(err, result) {
if(err) throw err;
});
}
for example this is what the result looks like(col is the primary key):
col | col2 | col3 | col4 | col5
---------+---------+-----------+--------+--------
8909265 | text | 8759 | 5332 | 7480
1769288 | text | 8759 | 5332 | 7480
I want to add a row for every single value in the array foo5. This is the expected result. How can I achieve this:
col | col2 | col3 | col4 | col5
---------+---------+-----------+--------+--------
8909265 | text | 8759 | 5332 | 1234
1769288 | text | 8759 | 5332 | 5678
3254786 | text | 8759 | 5332 | 9101112
4357234 | text | 8759 | 5332 | 1314151617
assuming foo5 = {1234, 5678, 9101112, 1314151617};
UPDATE:
after adding a recursive function as suggested by someRandomSerbianGuy this is what my code looks like:
function recursion(i, counter) {
var insert2 = "INSERT INTO content (col, col2, col3, col4, col5) VALUES (?, ?, ?, ?, ?);"
if(counter == i) {
return;
} else {
client.execute(insert2, [foo, foo2, foo3, foo4, foo5[i]], {prepare : true}, function(err, result) {
if(err) throw err;
recursion(++i, counter);
});
}
}
recursion(0, foo5.length);
I am still getting the same results.
Switch to a promisified client module and use an async function. You will need to research promises and async functions in Node. It will take a bit of time getting used to it, but is necessary because this type of problem happens all the time with callbacks.
Code will be simpler, and it will work in a more straightforward way, with one insert at a time:
async function insert(sql, data) {
for (let i=0; i<data.length; i++)
await client.insert(sql, data[i]);
}
This is because Node.js is asynchronous. You can use Promises for this, or recursive function instead for loop.
By using recursive function instead for loop you are enabling it to finish client.execute and than triggering it again with different data. By using for loop you are just calling client.execute bunch of times with same data.
Example (for recursion in Node.js, be aware that there are better ways to write this, but I wanted to make it simple so you would understand syntax):
function recursion(i, howManyTimes){ //First you define function
if(i === howManyTimes){ //If it's called enough times just escape recursion
return;
}else{
//Your code for DB should be here, after successful .execute call call line under this one!
recursion(++i, howManyTimes);
}
}
recursion(0, 5); //You can call your function now since you defined it

Get all items from the parent table, but switch out the foreign key with a column from the child table

I have two tables in mysql and I'm trying to make a query call. In the Item table, the tid is a foreign key, but in the query call, I want to get all the information in the Items table, but instead of getting the tid, I want to get the name of the Types the tid refers to. What is the proper query call here?
|_______Items______| |________Types______|
| id {PK} | | tid {PK} |
| name | | name |
| description | | description |
| tid {fk} | | |
app.get('/getData', function(req, res) {
var content = {};
mysql.pool.query('SELECT * FROM Items WHERE id=?', [req.query.id],
function(err, rows, fields) {
if (err) {
next(err);
return;
}
content.results = JSON.stringify(rows);
res.send(content.results);
});
});
I believe the correct query should be:
mysql.pool.query('SELECT * FROM Items INNER JOIN Types on Types.tid = Items.tid WHERE Items.id=?', [req.query.id],
This will return all the fields from both tables, but only show the row from Types where the tid is used in the row of Items which has the id passed in req.query.id
This is done using a SQL INNER JOIN - if you're not familiar with this way of joining tables, it's quite fundamental to SQL and you should study it.
P.S. If you want just a specific selection of columns from the two tables (as hinted at in the question), you can write it like this, for instance:
mysql.pool.query('SELECT Items.id, Items.name, Items.description, Types.name FROM Items INNER JOIN Types on Types.tid = Items.tid WHERE Items.id=?', [req.query.id],

use nodejs to query mysql database

I use mysql module nodejs-mysql
I have two tables, Their struct is like this:
Table nicks
id |nick |
--------------
1 |Arnold |
2 |Bob |
Table order
nick |money |
---------------
Arnold |12 |
Arnold |43 |
Arnold |3 |
Bob |32 |
Bob |2 |
I want get a json object whose struct is like this:
[
{id:1, nick:'Arnold', order:[{money:12},{money:43},{money:3}]},
{id:2, nick:'Bob', order[{money:32},{money:2}]}
]
so what should I do?I use nodejs
what I have try:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
db : 'db'
user : 'user',
password : 'secret'
});
connection.connect();
connection.query('select * from nicks',function(err,data){
//here I travese the data array,and select the order table to get the money filed data.
});
I know how to create a query with node.js, I just don't know a method to get the results I want.I don't know how to make a proper query.
Here's another solution:
var mysql = require('mysql');
var conn = mysql.createConnection({
host : 'localhost',
database : 'test',
});
var query = ' \
SELECT id, nicks.nick, GROUP_CONCAT(money) AS money \
FROM nicks, orders \
WHERE orders.nick = nicks.nick \
GROUP BY id';
conn.query(query, function(err, rows, fields) {
rows.forEach(function(row) {
row.order = row.money.toString().split(',').map(function(value) {
return { money : Number(value) };
});
delete row.money;
});
// as an example, we'll print the object as JSON
console.log(JSON.stringify(rows, null, 2));
});
Follow the documentation at https://github.com/felixge/node-mysql
You need to setup a connection and query the db
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
var queryString = "SELECT * FROM nicks n JOIN order o ON n.nick=o.nick";
connection.query(queryString, function(err, rows) {
var outputJSON = [];
for row in rows{
outputJSON.push(row);
}
return outputJSON.toJSON()
});
You need to implement the function toJSON that formats your output by picking only the desired fields you need for you JSON

Categories