Issuing Simple Queries
The most common interaction between
a program and a database is retrieving or fetching data. In standard
SQL, this process is performed with the
SELECT
keyword. With Perl and the DBI, we have far more control over the way
in which data is retrieved from the database. We also have far more
control over how to post-process the fetched data.
Retrieving data from a database using DBI is essentially a four-stage cycle:
The prepare stage parses an SQL statement, validates that statement, and returns a statement handle representing that statement within the database.
Providing the prepare stage has returned a valid statement handle, the next stage is to execute that statement within the database. This actually performs the query and begins to populate data structures within the database with the queried data. At this stage, however, your Perl program does not have access to the queried data.
The third stage is known as the fetch stage, in which the actual data is fetched from the database using the statement handle. The fetch stage pulls the queried data, row by row, into Perl data structures, such as scalars or hashes, which can then be manipulated and post-processed by your program.
The fetch stage ends once all the data has been fetched, or it can be terminated early using the
finish()method.If you’ll need to re-
execute()your query later, possibly with different parameters, then you can just keep your statement handle, re-execute()it, and so jump back to stage ...