[Israel.pm] Database Insertion

Gaal Yahas gaal at forum2.org
Fri Jun 17 07:07:35 PDT 2005

On Fri, Jun 17, 2005 at 04:53:23PM +0300, Uri Bruck wrote:
> >I am trying to insert random text into a MySQL field. I am having problem 
> >in (data = '$datafile') if the original data contain single quote ('). How 
> >can I automatically add a trailing slash if found before each single quote 
> >in the data?
> I use the DBI module for mysql. It has a quote class method that takes 
> escapes all the characters that need to be escaped.
> Suppose your database handle is $dbh, then instead of
> "data = '$datafile'"
> use:
> " data = ".$dbh->quote($datafile)

This works. A better approach is to use placeholders:

     $dbh->do(q{INSERT INTO table data = ?}, {}, $datafile);

(This also works with "prepare" and "execute".)

This is better because it's more readable, and because it's potentially
faster (under some conditions, the SQL can be parsed only once even if
you're doing multiple insertions with different data).

The various "bind_" methods may also come in handy.

Gaal Yahas <gaal at forum2.org>

More information about the Perl mailing list