Node JS mysql deleting multiple rows with an array of arrays - mysql

I need to make a query which would be able to delete multiple rows from my table. In order to do that I've created an arrays within array with values which need to be passed to that query. Here is my code:
var deleteRooms = [ [ 3, 23 ], [ 4, 23 ], [ 5, 23 ], [ 2, 23 ]];
connection.query("DELETE FROM rate_plans_rooms WHERE room_id = ? AND rate_plan_id = ? ",
[deleteRooms],function(err,results){
if(err){return console.log(err)}
else
{
console.log('sended');
}
});
But every time I receive an error like this:
{ Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check
the manual that corresponds to your MariaDB server version for the
right syntax to use near ' (4, 23), (5, 23), (2, 23) AND rate_plan_id
= ?' at line 1
How can I fix that and send my query properly?

A solution for your problem is to use 'IN' inside your query:
var deleteRooms = [[3,23],[4,23],[5,23], [2,23]];
connection.query("DELETE FROM rate_plans_rooms WHERE (room_id, rate_plan_id) IN (?)",
[deleteRooms],function(err,results){
if(err) return console.log(err)
else console.log('sended');
});

The accepted solution did not work for me as it would give an Error: ER_OPERAND_COLUMNS: Operand should contain 2 column(s) error. Instead, this worked for me:
var deleteRooms = [[3,23],[4,23],[5,23], [2,23]];
queryArray = Array(deleteRooms.length).fill('(?)'));
connection.query("DELETE FROM rate_plans_rooms WHERE (room_id, rate_plan_id) IN ("+queryArray.join(',')+")",
[deleteRooms],function(err,results){
if(err) return console.log(err)
else console.log('sended');
});

Related

Getting an error Error in executeUpdate, Table has no partition for value from column_list

I am getting an error "Error in executeUpdate, Table has no partition for value from column_list"
I have not used SQL in years.
This is the insert
INSERT INTO messages
(RunId, RunStart, RunFinish, ChannelId, StartMessageId,
FinishMessageId, Status, Error, NoOfMessages, NoOfFinalMessages,
NoOfMediaFiles, NoOfNewChannels)
VALUES ('635c8dd3-f476-49a1-8993-570dccb914e9', '2021-11-15 10:43:08.193',
'2021-11-15 10:43:08.211', 1, 1, 100, 'Success', null, 100, 50, 25, 5)
Reading the error, I think its treating one of the params as a list, am I right.

MySQL Insert and update multiple rows in Nodejs

I am using Express and MYSQL. This is my parameters
var values = [
[ 9, 1, 'input_4', 'Rj', 1 ],
[ 9, 2, 'input_1', 'hk', 1 ],
[ 9, 3, 'input_2', 'Vk', 1 ]
]
This is my Query
INSERT INTO
form_meta(form_id,sequence,meta_key,meta_label,is_active)
VALUES ?
which is working fine.
No i want if i pass
var values = [
[ 9, 1, 'input_4', 'Raj K', 1 ],
[ 9, 2, 'input_1', 'Kumar', 1 ],
[ 9, 3, 'input_2', 'Vinit Kumar', 1 ]
]
this needs to update not insert
I am using this query
var query = "INSERT INTO `form_meta`(`form_id`,`sequence`,`meta_key`,`meta_label`,`is_active`)
VALUES ? ON Duplicate Key sequence= VALUES(sequence)";
connection.query(query,[values],cb);
it gives me error
Error: ER_PARSE_ERROR: You have an error in your SQL syntax;
Any Idea?
It should be on duplicate key update sequence=values (sequence)

node mysql2 can't access update results

I'm doing a simple UPDATE with mysql2 :
UPDATE table1
SET table1.value1 = ?, table1.value2 = ?
WHERE user_id = (
SELECT user_id
FROM user
WHERE company_id = ?
)
table1 is related to the user table by user_id, but I only have the company_id so I do a subquery (probably should be a join, but thats another discussion):
const [results, buff] = await connection.execute(query, values);
return results
However, when accessing the results to make sure there are no errors and that only a single row is updated, results returns:
console.log
ResultSetHeader {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
info: 'Rows matched: 1 Changed: 0 Warnings: 0',
serverStatus: 2,
warningStatus: 0,
changedRows: 0
}
But I can't access the values. If I try results.affectedRows I get
Property 'affectedRows' does not exist on type 'RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[]'.
The only way to make it work is to do results['affectedRows']. Any suggestions?
So I forgot to mention that this is a typescript error, and I was able to fix it by doing:
const [results, buff] = await connection.execute(query, values);
const json: any = results;
return json.affectedRows //or whatever property I want
This also works:
const [results, buff] = await connection.execute(query, values);
return json as any; //then in the calling fuction access the properties I want

How do I use expression with bulk insert using npm mysql?

This question answers 99% of what I am looking for...
How do I do a bulk insert in mySQL using node.js
var sql = "INSERT INTO Test (name, email, n) VALUES ?";
var values = [
['demian', 'demian#gmail.com', 1],
['john', 'john#gmail.com', 2],
['mark', 'mark#gmail.com', 3],
['pete', 'pete#gmail.com', 4]
];
conn.query(sql, [values], function(err) {
if (err) throw err;
conn.end();
});
If I want to pass an expression, such as NOW(), how would I do that? If I pass it in the array, it would count as a string. Since VALUES is a ? that gets populated by the array, I can't easily inject an expression. Any ideas?
Basically it seems impossible, so you should make a query string you want.
I would try this as follows.
var sql = "INSERT INTO Test (name, email, n, modified_on) VALUES ?";
var values = [
['demian', 'demian#gmail.com', 1, '::NOW()'],
['john', 'john#gmail.com', 2, '::UNIX_TIMESTAMP()'],
['mark', 'mark#gmail.com', 3, '::DATE()'],
['pete', 'pete#gmail.com', 4, '::NOW()']
];
var formattedQuery = connection.format(sql, [values]).replace(/'::(.*?)'/g, '$1');
connection.query(formattedQuery, function(err) {
});
fomattedQuery is as follows.
INSERT INTO Test (name, email, n, modified_on) VALUES ('demian', 'demian#gmail.com', 1, NOW()), ('john', 'john#gmail.com', 2, UNIX_TIMESTAMP()), ('mark', 'mark#gmail.com', 3, DATE()), ('pete', 'pete#gmail.com', 4, NOW())
I hope this helps.

How do I do a bulk update in mySQL using node.js

i want to update data in bulk i have over 50 rows to be updated in an array of objects in node JS. something like
https://github.com/felixge/node-mysql
and How do I do a bulk insert in mySQL using node.js
var updateData=[
{a: '15',b: 1,c: '24',d: 9,e: 1,f: 0,g: 0,h: 5850,i: 78 },
{a: '12',b: 1,c: '21',d: 9,e: 1,f: 0,g: 0,h: 55,i: 78 },
{a: '13',b: 1,c: '34',d: 9,e: 1,f: 0,g: 0,h: 58,i: 78 },
{a: '14',b: 1,c: '45',d: 9,e: 1,f: 0,g: 0,h: 585,i:78 },
{a: '16',b: 1,c: '49',d: 9,e: 1,f: 0,g: 0,h: 85,i: 78 }
]
my query is : update table set a= updateData.a ,b= updateData.b ,c = updateData.c , d==updateData.d ,e=updateData.e,f=updateData.f where e=updateData.e
As of I know, there is no direct way to do bulk update records in mySQL. But there is a work around for this - You could execute multiple insert statements and then execute the query to achieve the desired result.
To do this, while creating a connection allow it to execute multiple statements as it is disabled by default.
var connection = mysql.createConnection({
host : dbConfig.host,
user : dbConfig.user,
password : dbConfig.password,
database : dbConfig.database,
multipleStatements: true
});
Then, construct the bulk update query in the below syntax by manipulating the inputs you have.
Query1; Query2; Query3;
Say, for Instance,
update table set a='15', b=1, c='24', d=9, e=1, f=0, g=0, h=5850, i=78;update table set a='12', b=1, c='21', d=9, e=1, f=0, g=0, h=5850, i=78;
Then, execute the query as usual,
connection.query(sqlQuery, params, callback);
Hope this helps.
You can accomplish this by enabling the multiple statements feature in your mysql connection. Then you can loop through your updateData and construct mysql statements separated by a ';'. You can see an example of this in this answer.
It's really not easy to bulk update data using node-MySQL but here you can do an alternative if you can use .map function in the frontend. Let me show you what i did with mine--
just make a single update API and use it like this in your frontend-
updateData.map((item, key)=>{
return (
axios.path('/api/update', {
a: item.a,
b: item.b,
c: item.c
})
).then(()=> console.log('updated'))
.catch((err)=> console.log(err))
})
there are couple ifs, but
if you have a unique constraint on column e
if you have a default values for all columns in the target table which are not affected by this query
then you can use this slightly nasty way:
const sql = `insert into table (a,b,c,d,e,f)
values ?
on duplicate key update
a = values(a),
b = values(b),
c = values(c),
d = values(d),
f = values(f)`
the use the query variant with passed values (updateData in your case):
connection.query(sqlString, updateData, callback)
your updateData should be an array of arrays of values to go into a,b,c,d,e,f columns
A little late answering, but using MySQL JSON_TABLE can help. Here's a working example:
UPDATE person a
INNER JOIN (
SELECT
personId, addressType, addressId
FROM JSON_TABLE('
[
{"personId": 318, "addressType": "Primary", "addressId": 712},
{"personId": 319, "addressType": "Shipping", "addressId": 712}
]',
'$[*]' COLUMNS(
personId INT PATH '$.personId',
addressType VARCHAR(10) path '$.addressType',
addressId INT path '$.addressId')
) a) b
ON a.personId = b.personId
SET
a.addressId = b.addressId,
a.addressType = b.addressType;