【问题标题】:Variable in MySQL Query causes errorMySQL 查询中的变量导致错误
【发布时间】:2012-01-09 05:16:27
【问题描述】:

我有一个 node.js 应用程序,它使用 node-mysql 来查询 MySQL 数据库。

问题:似乎当我将查询中的表名设为变量时,事情就停止了。我错过了什么吗?

工作节点代码

client.query('SELECT * from tableA',
                function(error, results, fields) {
                    if (error)
                        throw error;
                    callback(results);
                });

非工作节点代码

client.query('SELECT * from ?',
                [ tableA ],
                function(error, results, fields) {
                    if (error)
                        throw error;
                    callback(results);
                });

【问题讨论】:

标签: mysql node.js express


【解决方案1】:

您可能只是将表名附加到字符串(伪代码,我不知道 node.js)

client.query('SELECT * from ' + [tablaA],
                function(error, results, fields) {
                    if (error)
                        throw error;
                    callback(results);
                });

【讨论】:

  • 您在上一个问题stackoverflow.com/questions/8317472/… 中已经有了答案:)
  • 对,我想知道这是否适用于一般的 MySQL 查询,比如 PHP,或者这个 node.js 是特定的
  • 在 Mysql 中,表名不允许是准备好的语句中的变量(?),我猜 nodejs 正在后台执行准备好的语句。
【解决方案2】:

他们不工作的原因很清楚。

来自非工作代码的查询将是:

从'tableA'中选择 *

@Andreas 提供了一种解决方案,但在 where 语句或插入其他不希望像“null”值一样转义的值时,您也会遇到同样的问题。 (转换成字符串)

同样的问题here

查看source format && escape from node-mysql 的工作原理。

【讨论】:

  • 表名、数据库名、列名不能转义,而要添加到列和MySQL函数的值可以吗?
  • 我会说是的,占位符通常用于动态数据(参数)
猜你喜欢
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 2020-01-14
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
相关资源
最近更新 更多