文档中给出的例子如下:
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-mysql2
的node-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/