You can query databases to retrieve data at runtime. The retrieved data, called the record set, is stored on that page as a query object. A query object is a special entity that contains the record set values, plus RecordCount, CurrentRow, and ColumnList query variables. You specify the query object's name in the name attribute of the cfquery tag. The query object is often called simply the query.
The following is a simple cfquery tag:
<cfquery name = "GetSals" datasource = "CompanyInfo">
SELECT * FROM Employee ORDER BY LastName </cfquery>
Note: The terms "record set" and "query object" are often used synonymously when discussing record sets for queries. For more information, see Chapter 22, "Using Query of Queries".
When retrieving data from a database, perform the following tasks:
cfquery tag on a page.
cfquery block.cfoutput, cfgrid, cftable, cfgraph, or cftree.
The cfquery tag is one of the most frequently used CFML tags. You use it with the cfoutput tag to retrieve and reference the data returned from a query. When ColdFusion encounters a cfquery tag on a page, it does the following:
The following code shows the syntax for the cfquery tag:
<cfquery name="EmpList" datasource="CompanyInfo">
SQL code... </cfquery>
In this example, the query code tells ColdFusion to do the following:
When creating queries to retrieve data, keep the following guidelines in mind:
<cfquery> and ending </cfquery> tags, because the cfquery tag is a block tag.
name and datasource attributes within the opening cfquery tag.cfquery block.SELECT * FROM mytable WHERE FirstName='Jacob' selects every record from mytable in which the first name is Jacob. cfquery tag.cfoutput, cfgrid, cftable, cfgraph, or cftree later on the page.
As discussed earlier in this chapter, you build queries using the cfquery tag and SQL.
Note: This and many subsequent procedures use the CompanyInfo data source that connects to the company.mdb database. This data source is installed by default. For information on adding or configuring a data source, see Administering ColdFusion MX.
<html> <head> <title>Employee List</title> </head> <body> <h1>Employee List</h1> <cfquery name="EmpList" datasource="CompanyInfo"> SELECT FirstName, LastName, Salary, Contract FROM Employee </cfquery> </body> </html>
C:\CFusionMX\wwwroot\myapps\
http://127.0.0.1/myapps/emplist.cfm
Only the header appears, as the following figure shows:
ColdFusion creates the EmpList data set, but only HTML and text return to the browser. When you view the page's source, you see only HTML tags and the heading "Employee List." To display the data set on the page, you must code tags and variables to output the data.
The query you just created retrieves data from the CompanyInfo database. The following table describes the highlighted code and its function: