我还是ColdFusion的新手。基本上我是动态创建Oracle的查询。我过去使用过cfquery / cfparam,但我更愿意使用cfscript来实现,因为它更具可读性。它旨在成为一个大型的“INSERT ALL ... INTO。”
这是我到目前为止的基本示例:
<cfscript>
clinicNIL = structNew();
clinicNIL.ADDRESS1 = 'line 1';
clinicNIL.ADDRESS2 = 'line 2';
myFields = [
'ADDRESS1'
,'ADDRESS2'
];
query = queryNew("");
sql = "INSERT ALL";
for (i=1; i LTE ArrayLen(myFields); i=i+1) {
sql = sql & "INTO NOTINLIST (SOURCETABLE, SOURCECOLUMN, SOURCEPK, ENTEREDVALUE, INSERTDATE, UPDATEDDATE, INSERTEDBY, UPDATEDBY) VALUES(";
// [..]
// How to dynamically escape the value below?
sql = sql & EscapeTheParameterHere( clinicNIL[ myFields[i] ]);
// [..]
sql = sql & ")
";
}
WriteOutput( query );
</cfscript>
我有'EscapeTheParameterHere',我希望能够以某种方式逃脱这个价值。我该如何逃避价值?
虽然我在这里,CF有什么好的资源或参考资料吗?
答案 0 :(得分:4)
您可以使用cfscript查询对象的addParam函数绑定参数,就像cfqueryparam一样。不得不将你的例子转换成我的MSSQL盒子和你桌子的一个较小版本,但它应该给你一般的想法。
<cfscript>
clinicNIL = structNew();
clinicNIL.ADDRESS1 = 'line 1';
clinicNIL.ADDRESS2 = 'line 2';
myFields = [
'ADDRESS1'
,'ADDRESS2'
];
query = new query();
//you may need to use the query methods setDatasource, setUsername and setPassword to configure the query
//sql = "INSERT ALL" & chr(13) & chr(10);
sql = "";
for (i=1; i LTE ArrayLen(myFields); i=i+1) {
query.addParam(name="address"&i,value=clinicNIL[ myFields[i] ],cfsqltype="VARCHAR");
sql = sql & "INSERT INTO NOTINLIST (ADDRESS) VALUES(";
sql = sql & ":address" & i;
sql = sql & ")" & chr(13) & chr(10);
}
queryResult = query.execute(sql=sql);
</cfscript>
神奇的是sql字符串中的:paramName
将在执行调用期间使用正确的转义参数替换它的关联参数。
答案 1 :(得分:1)
这是我使用cfquery / cfqueryparam提出的解决方案。我没有意识到你可以在cfquery中做一个cfloop。顺便说一下,我确实找到了一个名为'CF.Query'的东西,但显然它只满足了cfquery的一个子集。
<cfscript>
clinicNIL = structNew();
clinicNIL.ADDRESS1 = 'line 1';
clinicNIL.ADDRESS2 = 'line 2';
myFields = [
'ADDRESS1'
,'ADDRESS2'
];
totalFields = ArrayLen(myFields);
</cfscript>
<cfquery name="insert" datasource="somedatasource">
INSERT ALL
<cfloop from="1" to="#totalFields#" index="i">
INTO NOTINLIST
(SOURCETABLE, SOURCEPK, SOURCECOLUMN, ENTEREDVALUE, INSERTDATE, UPDATEDATE, INSERTEDBY, UPDATEDBY)
VALUES(
'FACULTYADDRESSES'
, 123
, <cfqueryparam value = "#myFields[i]#" cfsqltype='CF_SQL_VARCHAR'>
, <cfqueryparam value = "#clinicNIL[ myFields[i] ]#" cfsqltype='CF_SQL_VARCHAR'>
, SYSDATE
, SYSDATE
, '123'
, '123'
)
</cfloop>
SELECT * FROM DUAL
</cfquery>