Avg. Rating 5.0

Problem

The application wants to set a default datasource for all queries instead of specifying the datasource attribute of the <cfquery> tag with every call.

Solution

ColdFusion 9 introduced the ability to set a default datasource for an application.

Detailed explanation

Before ColdFusion 9 every <cfquery> tag had to have a datasource attribute that specified the datasource for ColdFusion to execut the particular query on.

For example:

<cfquery datasource="wine" name="qGetWine">
SELECT
*
FROM
tbl_wine
</cfquery>

The above <cfquery> would select all records from the table tbl_wine in the database that was specified in the datasource.  One way around having to specify the datasource was to set an application variable to hold that value and then use that variable in place of the hardcoded value.

The same query from above using this method would look like this:

<cfquery datasource="#application.dsn#" name="qGetWine">
SELECT
*
FROM
tbl_wine
</cfquery>

With ColdFusion 9 all that has to happen is setting datasource variables in the Application.cfc

<cfcomponent>

<cfset this.name = "wineDB" />

<cfset this.datasource = "wine">

</cfcomponent>

Now, by having set this variable the application does not have to reference the datasource attribute when using <cfquery>.  The wine datsource will now be used by default if no datasource is specified.  This datasource will also be used with <cfstoredproc> as well.

So the example from above becomes:

<cfquery  name="qGetWine">
SELECT
*
FROM
tbl_wine
</cfquery>

This new feature will save lots of time!


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes