【发布时间】:2016-07-28 20:35:53
【问题描述】:
我正在使用 ColdFusion 并尝试创建一个函数,让我可以获取特定帐户中特定列的值(每个帐户都有自己的记录/行)。
这样的函数可以正常工作:
<cffunction name="getColumnValueFromAccount" access="public" returntype="string" >
<cfargument name="accountName" type="string" required="yes" />
<cfquery name="getColumn" datasource="mydatasource">
<!--- Note that the line below is 'hard-coded.' --->
SELECT role_ExampleSystem
FROM table_name
WHERE (accountName = <cfqueryparam cfsqltype="cf_sql_varchar" maxlength="50" value='#accountName#'>)
</cfquery>
<!--- It's easy to return the column value when you know what its name was. --->
<cfreturn getColumn.role_ExampleSystem >
</cffunction>
但我真正想要的是一个函数,它允许我指定从哪个列名读取,并且不需要制作一堆几乎相同的 CF 函数,它们只是具有不同的硬编码 SELECT 参数。我在想它应该看起来像这样,但我在实际读取我认为它应该返回的单个字符串时遇到了麻烦。
<cffunction name="getColumnValueFromAccount" access="public" returntype="string" >
<cfargument name="accountName" type="string" required="yes" />
<!--- Trying to accept a column name as an argument --->
<cfargument name="columnName" type="string" required="yes" />
<cfquery name="getColumn" datasource="mydatasource">
<!--- I'm trying to use cfqueryparam to add specify the column name to select. --->
SELECT <cfqueryparam cfsqltype="cf_sql_varchar" maxlength="50" value='#columnName#'>
FROM table_name
WHERE (accountName = <cfqueryparam cfsqltype="cf_sql_varchar" maxlength="50" value='#accountName#'>)
</cfquery>
<!--- This line doesn't work. --->
<cfreturn getColumn[#columnName#] >
</cffunction>
我认为您可以在 getColumn[#columnName#] 或 getColumn[columnName] 这样的括号符号中使用变量,因为有人在 comment 中提到了它。但是当我自己尝试使用变量时,它并没有按预期工作。我收到此错误:
The value returned from the getColumnValueFromAccount function is not of type string. If the component name is specified as a return type, it is possible that either a definition file for the component cannot be found or is not accessible.
知道当我想获得 cfquery 的单个结果时应该采取什么路线,但我没有在查询的 SELECT 部分使用硬编码的列名吗?通常这个过程很简单,但是当你的列名是一个变量时,情况似乎有点不同。
【问题讨论】:
-
我正在尝试使用 cfqueryparam 添加指定要选择的列名。 你不能那样做。 CFQueryparam 只能用在文字上,不能用在必须作为 sql 命令评估的东西上——比如表名或列名。
-
这可能是问题的一部分,从技术上讲,我不需要 cfqueryparam 提供的 SQL 注入保护,因为 columnName 的 cfargument 将是我在另一个服务器端函数中指定的内容。无需清理输入,因为我知道这将是我写的有效内容。
-
我按照您的建议删除了
cfqueryparam并替换为#variable#然后使用 Mark A Kruger 的更正示例来说明如何使用括号表示法。看起来它正在按预期工作!我会在最后发布我所拥有的,以防将来对人们有所帮助。
标签: sql coldfusion cfquery cfqueryparam