Skip to Main Content
Programming the Perl DBI
book

Programming the Perl DBI

by Tim Bunce, Alligator Descartes
February 2000
Intermediate to advanced content levelIntermediate to advanced
364 pages
11h 47m
English
O'Reilly Media, Inc.
Content preview from Programming the Perl DBI

Database-Specific Quote Handling

By far the most important utility method is quote() , which correctly quotes and escapes SQL statements in a way that is suitable for a given database engine. This feature is important if you have a Perl string that you wish to insert into a database, as the data will be required, in most cases, to have quotation marks around it.

To confuse matters, database engines tend to have a different format for specifying these surrounding quotation marks. DBI circumvents this problem by declaring the quote() method to be executed against a database handle, which ensures that the correct quotation rules are applied.

This method, when executed against a database handle, converts the string given as an argument according to defined rules, and returns the correctly escaped string for use against the database.

For example:

#!/usr/bin/perl -w
#
# ch04/util/quote1: Demonstrates the use of the $dbh->quote() method

use DBI;

### The string to quote
my $string = "Don't view in monochrome (it looks 'fuzzy')!";

### Connect to the database
my $dbh = DBI->connect( "dbi:Oracle:archaeo", "username", "password" , {
    RaiseError => 1
} );

### Escape the string quotes ...
my $quotedString = $dbh->quote( $string );

### Use quoted string as a string literal in a SQL statement
my $sth = $dbh->prepare( "
    SELECT *
    FROM media
    WHERE description = $quotedString
  " );
$sth->execute();

exit;

For example, if you quoted the Perl string of Do it! via an Oracle database handle, you would be returned ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Perl Programming, 2nd Edition

Advanced Perl Programming, 2nd Edition

Simon Cozens
Perl One-Liners

Perl One-Liners

Peteris Krumins
Advanced Perl Programming

Advanced Perl Programming

Sriram Srinivasan
Beginning Perl

Beginning Perl

Curtis Ovid Poe

Publisher Resources

ISBN: 1565926994Supplemental ContentErrata Page