in reply to Backslashes with DBI quote( ) and MySQL
This sample script will insert your values escaping them with placeholders. Then it repeats the same operation using the quote() method.#!/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: <\> <\\> <\\\> <'> <''> <\"> <"> <\"> <'"'> <\> <\\> <\\\> <'> <''> <\"> <"> <\"> <'"'>
As long as you can manipulate your string with Perl, you can always turn it into an hex string, solving any possible quotes problem. The drawback is that your string in the query will be twice as long as the original. It's important to bear that in mind when you calculate the size of your query.my $hexstr = "0x" . unpack("H*", $barestr); $dbh->do(qq{insert into test_chars values( $hexstr )}); # notice that the hexstring has NO QUOTES
Another client, mysqldump will escape our data:mysql> select * from test_chars; +-------+ | quote | +-------+ | \ | | \\ | | \\\ | | ' | | '' | | \" | | " | | \" | | '"' | +-------+ 9 rows in set (0.00 sec)
HTH# # 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 ('\'\"\'');
_ _ _ _ (_|| | |(_|>< _|
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Backslashes with DBI quote( ) and MySQL
by doran (Deacon) on Mar 06, 2002 at 18:13 UTC |