Node.js 和 node-mysql DB 查询 - 需要同步代码帮助
我正在编写一些非 Web 应用程序帮助程序,并且遇到了同步查询调用的需要。
基本上,在一个循环中,我需要检查数据库以查看该值是否存在。如果没有,则插入该值。目前,对于node-mysql,我只能让它与回调一起工作。因此,node.js 将调用视为异步,并在查询完成之前继续处理我的请求。这是一个大问题,因为最终可能会插入重复项,因为它们在队列中。
理想的解决方案 - 不起作用。结果实际上是客户端的对象,我在里面找不到实际的结果。然而,这确实使其同步。
results = client.query('SELECT COUNT(md5) as md5Count FROM table WHERE md5 = "' + md5 + '"')
以下不起作用。 Node.js 将其视为异步,outerResult 仍然是 client 的对象。
outerResult = client.query('SELECT COUNT(md5) as md5Count FROM board WHERE md5 = "' + md5 + '"', function selectCb(err, results, fields) {console.log(results);});
任何帮助表示赞赏。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题最好用 SQL 来解决。您不能通过重复与数据库对话来解决此问题,而是通过让 SQL 仅在索引值尚不存在的位置插入来解决此问题。
这是一个超级简化的示例,并不是最优化的。如果您愿意,您可以在这里对数据集执行相同的操作,而不是逐条记录。
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.
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.
异步解决方案总是存在的。
基本上您担心可能会输入重复的条目。
我假设您有一组数据要循环。您的问题已通过
_.uniq
或其他过滤器解决方案解决。所以你只需调用
_.uniq(md5s).forEach(function() { })
There is an asynchronous solution, there always is.
basically your worried that duplicate entries could be entered.
I presume you have an array of data to loop through. Your problem is solved with
_.uniq
or some other filter solution.So you simply call
_.uniq(md5s).forEach(function() { })