Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

node.js - Updating multiple rows with node-mysql, NodeJS and Q

I am using node-mysql, node-js, and Q promises.

I have successfully updated, deleted, and inserted single rows using the above. As well as inserted multiple rows in a single statement in my test case scenario.

However, I need to update multiple rows with different values (batch mode) either in a single query or in a for loop.

The information on how to use prepared statements in mysql2 (supposed to improve on node-mysql) is very sparse and there are no examples, although that should be the natural choice, together with promises to compensate for node-js asynchronous nature.

In addition, I have successfully used defered.makeNodeResolver() in various test scenarios.

I am trying to update multiple rows in a single query with a where clause and changing conditions.

It is working when I update a single row. However, when I try to update multiple rows with a single query, the records aren't updated.

I am ready to switch to using a for loop to perform multiple updates and then aggregate the result and send it back from the server to the client, which would have been my second preferred choice. And I don't see why it shouldn't be done that way if there isn't too much of a performance hit. But I haven't found any examples for doing it that way.

var values = [
    { users: "tom", id: 101 },
    { users: "george", id: 102 }
    ];

    // var params = [values.users, values.id ];

    var sql = 'UPDATE tabletest SET users = ? WHERE id = ?;';


    connection.query(sql, [{users: values[0].users}, {id: values[0].id }], defered.makeNodeResolver());

The code shown above isn't actually updating multiple rows. I imagine there's an error in my syntax.

But anyway, what is the best approach to go about this in this particular scenario? Prepared statements, repeated queries in a for loop, or stored procedures?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it this way:

var values = [
  { users: "tom", id: 101 },
  { users: "george", id: 102 }
];
var queries = '';

values.forEach(function (item) {
  queries += mysql.format("UPDATE tabletest SET users = ? WHERE id = ?; ", item);
});

connection.query(queries, defered.makeNodeResolver());

To use multiple statements feature you have to enable it for your connection:

var connection = mysql.createConnection({
  ...
  multipleStatements: true,
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...