Saturday, August 25, 2018

Node.js and node-mysql DB Query - need synchronous code help



I am writing some non-web app helper, and came across a need for a synchronous query call.



Basically, within a loop I need to check the database to see if the value exists. If it doesn't then insert the value. Currently, with node-mysql I can only get it to work with a callback. Because of that, node.js treats the call as asynchronous and keeps processing my request before the query is finished. This is a big issue because in the end it could be inserting duplicates because they were in the queue.



Ideal Solution - doesn't work. Results is actually the object of client, and I can't find the actual results within. However this does make it synchronous.




results = client.query('SELECT COUNT(md5) as md5Count FROM table WHERE md5 = "' + md5 + '"')


The following does not work. Node.js treats it as asynchronous, and outerResult is still the object of client.



outerResult = client.query('SELECT COUNT(md5) as md5Count FROM board WHERE md5 = "' + md5 + '"',  function  selectCb(err, results, fields) {console.log(results);});


Any help is appreciated.



Answer




Basically, within a loop I need to check the database to see if the value exists. If it doesn't then insert the value.




This is a problem best served with SQL. You don't solve this problem by talking to the database repeatedly, you solve this problem by having SQL only insert where the index value doesn't already exist.



INSERT INTO mytable ( name, address ) 
SELECT @name, @address FROM DUAL
WHERE NOT EXISTS (SELECT * FROM mytable WHERE name = @name, address = @address)



This is a super simplified example, and not the most optimized. You can do the same thing here with sets of data, instead of record by record, if you like.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...