Introducing cfquery

The cfquery tag is the main tag used by ColdFusion to interact with databases. Using cfquery, you can pass any Structured Query Language (SQL) statement to a data source registered with the ColdFusion Administrator. The content of your SQL statements determines what action is performed against the data source. The next section provides a quick primer on SQL.

The cfquery tag works by establishing a connection with the specified data source, passing a series of SQL commands, and returning query variables that contain information about the operation. The basic syntax for using the cfquery tag is as follows:

<cfquery name="query_name"
         datasource="datasource_name">
SQL statements
</cfquery>

Each attribute in the opening cfquery tag specifies information about the data source and how ColdFusion should access it. The name attribute assigns a name to the query. Valid query names must begin with a letter and can contain only letters, numbers, and underscore characters. name is required when passing an SQL SELECT statement and is optional for all other SQL operations.[2] The datasource attribute is required in all circumstances except when dbtype is Query (covered later in Chapter 11) and specifies the name of the data source (as it appears in the ColdFusion Administrator) to connect to when executing the query. There are a number of additional attributes that can be used with the cfquery tag. For a complete list, see its tag reference in Appendix A.



[2] Although the name attribute is required only for SQL SELECT statements, you may wish to use it with all your queries. It makes debugging easier, especially for templates that contain multiple queries, because it allows you to identify each query by name in the debug output.

Get Programming ColdFusion MX, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.