Developing Web Applications with ColdFusion
|
|
Chapter 3 : Querying a Database
|
Retrieving Data
You can query databases to retrieve data at runtime. When retrieving data from a database:
- You use the CFQUERY tag on a page to tell ColdFusion how to connect to a database and how to store the retrieved data.
- You write SQL commands inside the CFQUERY block to specify the data that you want to retrieve from the database.
- The retrieved data is stored on that page as a query variable.
- You can reference the query variable data on that page in a CFOUTPUT block to use its values.
The CFQUERY Tag
The CFQUERY tag is one of the most frequently used CFML tags. You use it in conjunction with the CFOUTPUT tag so that you can retrieve and reference the data returned from a query.
When ColdFusion encounters a CFQUERY tag on a page, it does the following:
- Connects to the specified data source.
- Performs SQL commands that are enclosed within the block.
- Returns query variable values to the page.
CFQUERY tag syntax
<CFQUERY NAME="EmpList" DATASOURCE="CompanyInfo">
You'll type SQL here
</CFQUERY>
In this example, the query code tells ColdFusion to:
- Use the
CompanyInfo
data source to connect to the company.mdb
database.
- Store the retrieved data in the query variable EmpList.
In general, you should follow these guidelines:
- The CFQUERY tag is a block tag, that is, it has an opening <CFQUERY> and ending </CFQUERY> tag.
- Use the NAME attribute to name the query variable so that you can reference it later on the page.
- Use the DATASOURCE attribute to name an existing data source that should be used to connect to a specific database.
- Always surround attribute values with double quotes (").
- Place SQL statements inside the CFQUERY block to tell the database what to process during the query.
- When referencing text literals in SQL, use single quotes ('). For example,
Select * from mytable WHERE FirstName='Russ'
selects every record from mytable in which the first name is Russ.
Note |
The data source must exist in order to perform a successful query.
|
Copyright © 1999, Allaire Corporation. All rights reserved.
|
|