| Online Eiffel Documentation

EiffelStudio

# Query variables

If you have to execute database queries which only differ in the expression values, you can create a template query and then bind variables into this template for each execution.

This mechanism can be applied for requests with a result (DB_SELECTION) or without (DB_CHANGE). Hence both classes inherits from STRING_HDL that actually handle variable binding.

To use variable binding:

- Create a template query.
- Bind variables to the query.

## Creating a template query

Template queries are parsed to replace each variable by its bound value. To create a template query, you have hence to put directly variables where the values would take place.

Variables syntax is simple: the ':' special character followed by the variable name.

    	selection: DB_SELECTION
    	Bind_var: STRING is "firstname"
    	...
    	create selection.make
    	selection.set_query ("Select * from CONTACTS where Firstname = ':" + Bind_var + "'")

Note: The code example shows how to bind variables to a DB_SELECTION object but the mechanism is exactly the same for DB_CHANGE objects.

## Binding variables to a query

Once you have created your query, you can map variable names to values and execute the query:

    	selection: DB_SELECTION
    	Bind_var: STRING is "firstname"
    	...
    	loop
    		io.read_line
    		selection.set_map_name (io.laststring, Bind_var)
    		selection.execute_query
    		...
    		selection.unset_map_name (Bind_var)
    	end

See Also
Performing a database selection.
Modifying database content.