When they are used in a ColdFusion page, queries are nothing more then a few lines of code within cfquery tags. If you have to build a site that contains both a front end and back end, you will most certainly bump into situations where you have two pages that use data retrieved by identical recordsets, and which should change at the same time. One solution is to create an identical recordset on each page (see Figure 1).
Figure 1. Two cfqueries that retrieve the same data
As you can see, the two code bits are identical, using the same query:
SELECT * FROM BOOKS ORDER BY BOOKID ASC
After you see the actual problem, the solution of using two different recordsets is not such a great one because it wastes time and lacks the possibility of changing everything at once. There must be some easier way to do this without writing the same code twice, while taking into consideration efficiency and maintainability.
If you think like this too, you can quickly come up with some ideas on how to save time:
Since the introduction of ColdFusion components (CFCs) in ColdFusion, they've been seen as great tools when it comes to code reuse. And because extracting and manipulating database information in pages actually means writing code, why not pack this code into a component and use it in different pages? Well, as Ben Forta's article shows, and as you'll see in this section, you can do this to implement query reuse. In this article, I refer to "cfcquery" as a cfquery inside a ColdFusion component.
Take a look at the following component code that implements the listing of all books in a library. As you can see in Figure 2, books are sorted by title in an ascending order.
Figure 2. Hand-coded cfcquery that retrieves the book list
If you want to display the title of the first record from the ones returned by this query, you'll have to enter the following code:
<cfoutput>#booklisting.title#</cfoutput>
This is a good example of using components to keep the query in one place. This has some advantages and some (huge) disadvantages.
Start with the bright side, the advantages:
Now for the disadvantages:
In summary, this approach cuts off the Dreamweaver visual capabilities when working with dynamic data. In the ColdFusion MX 7 approach, CFMX7 Extensions keep the advantages and eliminate the disadvantages by recognizing ColdFusion component code that returns a query as a recordset and adding it to the Dreamweaver data structure. This way you can use it in all dynamic elements without writing a single line of code.
The next section shows you how to create a query visually inside a component.