shemp has asked for the wisdom of the Perl Monks concerning the following question:
Pretty basic, given a db handle and a query, prepare()'s and execute()'s it, returning the executed handle, doing error checking along the way.sub safe_query_execute { my ($db_handle, $query) = @_; my $query_handle = $db_handle->prepare($query) or confess "Error preparing query: $query\n" . "Error: $DBI::errstr\n"; eval { $query_handle->execute(); }; if ( $@ ) { confess "QUERY ERROR: $DBI::errstr\n" . "QUERY: $query\n"; } return $query_handle; }
Yes, i'm aware that i could accomplish this other ways, but I dont necessarily want to execute all queries this way in a script, some queries will want some of their own specialized error checking, like recovering from the error, etc. I wrote this because I write similar code often in my scripts, so i wrapped it.
Note, i used or confess on the prepare(), and eval{} on the execute() - opinions on that could be another thread.
Anyhow, i want to write a nice (similar) wrapper for queries with input bind params. The problem im running into is getting the query for error statements. I'd like the function to look something like:
I dont want to have to pass in the query, sometimes they're created on the fly, and are out of scope when the handles are executed, but i cant find any way to get the query out of the handle itself. Is this possible?sub bind_param_safe_query_execute { my ($query_handle, @params) = @_; eval { $query_handle->execute(@params); }; if ( $@ ) { confess "QUERY ERROR: $DBI::errstr\n" # somehow print the query } }
Any other approaches to accomplish this same idea?
Note: someday i'll perhaps add stuff for giving SQL_TYPES to the bind params, perhaps with a Tie::IxHash instead of an array. Perhaps other options eventually too.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: DBI - get info from statemet handles
by blokhead (Monsignor) on Sep 29, 2004 at 19:34 UTC | |
|
Re: DBI - get info from statement handles (ShowErrorStatement)
by htoug (Deacon) on Sep 30, 2004 at 05:28 UTC | |
|
Re: DBI - get info from statemet handles
by ezra (Scribe) on Sep 29, 2004 at 19:39 UTC |