#!/usr/bin/perl -w
use strict;
use DBI;
# change the connect statement according to your needs
my $dbh = DBI->connect("DBI:mysql:test;host=localhost;"
."mysql_read_default_file=$ENV{HOME}/.my.cnf",
undef,undef,{RaiseError => 1});
my @quotes = ("\\", "\\\\", "\\\\\\",
"'", "''", "\\".'"', '"', "\\".'"', "'" . '"' . "'");
$dbh->do(qq{drop table if exists test_chars});
$dbh->do(qq{create table test_chars (quote char(5))});
my $sth = $dbh->prepare(
qq{insert into test_chars values ( ? ) }
);
for (@quotes) {
$sth->execute( $_ );
}
print_chars();
print "\n";
$dbh->do(qq{delete from test_chars});
for (@quotes) {
my $quoted = $dbh->quote($_);
$dbh->do( qq{insert into test_chars values ($quoted)});
};
print_chars();
sub print_chars {
my $aref = $dbh->selectall_arrayref(
qq{select * from test_chars}
);
for my $row (@$aref) {
for my $field(@$row) {
print "<$field>\t";
}
print "\n"
}
}
$dbh->disconnect();
__END__
output:
<\>
<\\>
<\\\>
<'>
<''>
<\">
<">
<\">
<'"'>
<\>
<\\>
<\\\>
<'>
<''>
<\">
<">
<\">
<'"'>
####
my $hexstr = "0x" . unpack("H*", $barestr);
$dbh->do(qq{insert into test_chars values( $hexstr )});
# notice that the hexstring has NO QUOTES
####
mysql> select * from test_chars;
+-------+
| quote |
+-------+
| \ |
| \\ |
| \\\ |
| ' |
| '' |
| \" |
| " |
| \" |
| '"' |
+-------+
9 rows in set (0.00 sec)
####
#
# Dumping data for table 'test_chars'
#
INSERT INTO test_chars VALUES ('\\');
INSERT INTO test_chars VALUES ('\\\\');
INSERT INTO test_chars VALUES ('\\\\\\');
INSERT INTO test_chars VALUES ('\'');
INSERT INTO test_chars VALUES ('\'\'');
INSERT INTO test_chars VALUES ('\\\"');
INSERT INTO test_chars VALUES ('\"');
INSERT INTO test_chars VALUES ('\\\"');
INSERT INTO test_chars VALUES ('\'\"\'');
####
_ _ _ _
(_|| | |(_|><
_|