使用数据库
ColdFusion 的优势之一是使用数据库是多么容易。当然,查询输入可以并且应该参数化。
标签实施
<cfquery name="myQuery" datasource="myDatasource" result="myResult">
select firstName, lastName
from users
where lastName = <cfqueryparam value="Allaire" cfsqltype="cf_sql_varchar">
</cfquery>
CFScript 实施
// ColdFusion 9+
var queryService = new query(name="myQuery", datasource="myDatasource");
queryService.addParam(name="lName", value="Allaire", cfsqltype="cf_sql_varchar");
var result = queryService.execute(sql="select firstName, lastName from users where lastName = :lName");
var myQuery = result.getResult();
var myResult = result.getPrefix();
// ColdFusion 11+
var queryParams = {lName = {value="Allaire", cfsqltype="cf_sql_varchar"}};
var queryOptions = {datasource="myDatasource", result="myResult"};
var myQuery = queryExecute("select firstName, lastName from users", queryParams, queryOptions);
插入值同样简单:
queryExecute("
insert into user( firstname, lastname )
values( :firstname, :lastname )
",{
firstname: { cfsqltype: "cf_sql_varchar", value: "Dwayne" }
,lastname: { cfsqltype: "cf_sql_varchar", value: "Camacho" }
},{
result: "local.insertResult"
});
return local.insertResult.generated_key;