in reply to (jefffa) Re: Database Problems
in thread Database Problems

I agree with Jeffa absolutely 100%. I have one caveat though:

I like use "?" to indicate where I'll be filling in data. I do this so that I can have one generic subroutine that I can call from almost anywhere. Here is such a subroutine that I can pull off the top of my head:

# assume strict, and all other typical good code practices my $column = "UserName"; my $condition = "UserID"; my $qualifier = "101"; my ($rowcount, $UserID) = SQL_select($column, $condition, $qualifier); sub SQL_select { my $col = shift; my $cond = shift; my $qual = shift; my $sth = $dbh->("SELECT ? FROM DB.Table WHERE ? = ?"); $sth->execute($col, $cond, $qual); my $rowcount = $sth->rows; my $UserID = $sth->fetchrow_hashref; return ($rowcount, $UserID); }

Now, all you have to do is make sure you define the column, condition and qualifiers as needed. Of course, you'd probably want to get more complicated than this. You'd probably want some error checking and what-not (I'm on lunch...didn't get to stick it in there).

As a side note, notice I counted the rows. I've always done that, and I think it's a good idea (even if you're using a LIMIT function in the Database query) as a form of error checking. Obviously, this is a generic subroutine...so who knows what the guy is looking for. Supposing he is doing a query to find a UserName for someone with a UserID of 101 (as in this case). Well, if there are no rows returned, you'll probably want to report that the user doesn't exist. Or, if more than one is returned, you'll want to maybe take some other measures to notify the system maintainer that there is more than one UserName registered to that UserID. A whole set of other subroutines might be called if this is the case. So, it's always good to count rows.

--Coplan

Replies are listed 'Best First'.
Re: Re: (jefffa) Re: Database Problems
by mpeppler (Vicar) on Apr 17, 2003 at 00:32 UTC
    my $sth = $dbh->("SELECT ? FROM DB.Table WHERE ? = ?");
    Just a portability warning: Using placeholders for column names is very specific to the DBI driver for MySQL - this will not work with Oracle, Sybase, MS-SQL, etc.

    Michael

      Using placeholders for column names is very specific to the DBI driver for MySQL

      And it's specific to current versions of MySQL. When prepared queries are supported (soon, from the sound of it), that trick won't work.