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 the value of 'Do it!'.
However, the quote() method also takes care of
cases such as Don't do
it! which needs to be translated to
'Don''t do
it!' for most databases. The simplistic addition
of surrounding quotes would have produced 'Don't
do it!' which is not a valid
SQL string literal.
Some databases require a more complex quote()
method, and some drivers (though not all) have a
quote() method that can cope with multiline
strings and even binary data.