in reply to Escaping SQL correctly

> I'm sure DBI has some way to do this

Yes, they're called placeholders. See the DBI docs for prepare() and execute(). Or withouth placeholders see the quote() method.

> but I can't work out how I would go about creating a DBI object without a database to connect to

I'm not really sure what you mean. Don't you want to connect to a database and send the escaped SQL to it? If you just want to run DBI and DBD::Pg without connecting to a specific datbase, you can connect to one of the system databases (see the Pg docs for their names).

> or how I would intercept the escaped SQL.

Again, I don't know what you mean by intercept, but my $escaped_value = $dbh->quote($unescaped_value) should do the escaping.

Replies are listed 'Best First'.
Re^2: Escaping SQL correctly
by Anonymous Monk on Mar 08, 2006 at 01:46 UTC

    Don't you want to connect to a database and send the escaped SQL to it?

    No.

    I need to generate correctly-formed SQL statements to use in a report, which will then be reviewed by human eyes before entered in a database.

    That quote method looks promising, but I'd still need a handle. Is there any way to construct one without actually creating a database connection?

      Well, as I mentioned you can connect to one of the Pg system tables if you have access to Pg at all. If you don't, you may actually be able to do something like this (note no DBI or connection):
      use DBD::Pg; my $foo = q{foo'bar'baz}; print DBD::Pg::db->quote($foo); # prints 'foo''bar''bas'

        Thanks!

        I'll probably go with this solution, and if I can't get it to work I'll just install another copy of Postgres and use the template1 database and the quote method. I can write a wrapper that does the placeholder-style operation on my own, I think.

        Your help is much appreciated!