mysql - 如何使用 node.js 上的 mysql2 包使用准备好的查询

标签 mysql node.js

文档中给出的例子如下:

var mysql      = require('mysql2');
var connection = mysql.createConnection({ user: 'test', database: 'test'});

connection.execute('SELECT 1+? as test1', [10], function(err, rows) {
  //
});

这里的想法是“?”在查询中被替换为“10”的值。此示例显示如何使用替换值为“10”的查询一次。如何使用不同的替换值多次使用准备好的查询?这里的希望是已经编译了一个准备好的查询,因此对该查询的多次调用不会导致每次运行时编译查询的性能下降。

谢谢 - 加里

最佳答案

看起来像the source code 所建议的那样,这些语句真的已经准备好并缓存起来了。 :

Execute.prototype.start = function(packet, connection) {
  var cachedStatement = connection.statements[this.query];
  if (!cachedStatement) { // prepare first
    connection.writePacket(new Packets.PrepareStatement(this.query).toPacket(1));
  } else {
    this.statementInfo = cachedStatement;
    return this.doExecute(connection);
  }
  return Execute.prototype.prepareHeader;
};

this comment 证实了这一点关于关于node-mysql2node-mysql问题,库作者:

its prepared once and can be used many times.

这个评论线程还讨论了准备语句的驱逐策略:LRU 或 MRU,这与 node-mysql2 确实准备和缓存语句的事实一致(这是甚至在 source code 中被标记为 TODO)。

关于mysql - 如何使用 node.js 上的 mysql2 包使用准备好的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22178736/

相关文章:

mysql - 创建表时外键约束格式不正确

mysql - 通过在 SQL 中连接相同模式的 2 个表来查找列的总和和最大值

php - 创建基于用户兴趣的推荐算法

php - PDO 添加单引号绑定(bind)参数

node.js - NodeJS 与 Docker-compose

node.js - 防止 NodeJS 中的 MongoDB 多重连接

MySQL 错误代码 1111 : Invalid use of group function

node.js - 打开 Visual Studio 项目/解决方案时如何自动启动 grunt watch?

python - 以编程方式获取给定 PID 的子进程列表

node.js - _http_server.js :192 throw new RangeError (`Invalid status code: ${statusCode}` );