stonecolddevin has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I have a DBI snippet that's supposed to insert data into a MySQL data base taking 2 parameters, one of which I need to be an array.
For example, if calling the sub looks like this:
$db->insert('table_name', @values);
Values is my array, and it needs to contain data which will be join'd by commas (,). I can't figure out how to use an array as a parameter though.
I'd like my sub to look like this:
sub insert { my $self = shift; my @values = @the_array_parameter; my $query = "INSERT INTO " . $q[0] . " VALUES( " . join (',', @values); $dbh->do($query); }
I'm probably over thinking this, but any help is appreciated.

All posts are spawns of an archaeic and instinctual remnant of pre-neanderthalian neural synapse that, while irrevocably human, remains an anomoly to the common laws of nature.

Replies are listed 'Best First'.
Re: Need an array as a function parameter
by blue_cowdawg (Monsignor) on Mar 27, 2004 at 21:26 UTC

        I'm probably over thinking this, but any help is appreciated.

    You are and you almost had it. Here is almost the same function with corrections.

    sub insert { my ($self,$table,@values)=@_; my $query = sprintf("insert into %s values (%s);", $table,join(",",@values)); $dbh->do($query); }

    Having said that I am wondering why you aren't doing something like:

    : : my $sql=sprintf("insert into %s values (%s);",$table, join(",",map{ "?" } @values)); my $sth=$dbh->prepare($sql) or die $dbh->errstr; $sth->execute(@values) or die $sth->errstr;
    The reason I am asking is you may get into quoting issues they way you are proceeding and the DBI interface takes care of that for you behind the scenes. Also using the "die" setup as I show it will allow you to (hopefully) catch errors.

    The other thing I find curious is the lack of field names in your insert statement. I'm not a SQL guru and I haven't tried what you are proposing but I've sorta taken it on faith that it is at least a good idea to provide the field names in an insert statement.


    Peter L. Berghold -- Unix Professional
    Peter at Berghold dot Net
       Dog trainer, dog agility exhibitor, brewer of fine Belgian style ales. Happiness is a warm, tired, contented dog curled up at your side and a good Belgian ale in your chalice.
      Field names are optional in an SQL insert statement provided you fill all fields. Of course it doesn't make for very readable code.

      Omitting the field names might perhaps be a little faster as your database-engine does not have to map the values to the field names and can just sequentially fill all the fields. (I didn't benchmark it, I'm just guessing).

      CountZero

      "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

        The trouble with omitting column names in the insert statement is that, if your database structure ever changes, your code will magically start breaking, but it won't necessarily be obvious why. So it's less robust, as well as being less readable.

        Perhaps dhoss might want to consider (sorry, this is untested):

        sub insert { my $self = shift; my ($table, $columns, $values) = @_; my $sql = sprintf("insert into %s (%s) values (%s)", $table, join(',', @$columns), join(',' map { '?' } @$values); my $sth = $dbh->prepare($sql) or die $dbh->errstr; $sth->execute(@$values) or die $sth->errstr; }

        You'd call it as

        $obj->insert($tablename, \@column_names, \@values)
        It will give you a reasonably useful error message (at least in MySQL) if the table structure stops matching the column names in your code. Plus, using ? placeholders in the prepared statement, and passing the values to execute will handle all the quoting issues for you.

        Note I wouldn't use this, or any of the alternatives so far, any place I expected to get called repeatedly (e.g., in a loop). IIRC preparing a statement, either explicitly or via do is often a more expensive operation than executing it, so you'd want to pull the prepare out of your loop somehow, or else memoize the prepared statement.

        HTH,
        optimist

      Ahh, close I was. </yoda_voice>
      I haven't used sprintf ever, so that's why I didn't try that, I suppose.
      Now, how would I call that sub, with the appropriate parameters?

      All posts are spawns of an archaeic and instinctual remnant of pre-neanderthalian neural synapse that, while irrevocably human, remains an anomoly to the common laws of nature.

            Now, how would I call that sub, with the appropriate parameters?

        In your original post you have:

        $db->insert("table",@parms);
        and the answer I gave you will work for your purposes. I'm just puzzled ever so slightly by your methodology...


        Peter L. Berghold -- Unix Professional
        Peter at Berghold dot Net
           Dog trainer, dog agility exhibitor, brewer of fine Belgian style ales. Happiness is a warm, tired, contented dog curled up at your side and a good Belgian ale in your chalice.
Re: Need an array as a function parameter
by cchampion (Curate) on Mar 27, 2004 at 21:42 UTC

    blue_cowdawg has given you a fine solution.

    For more on the same subject, and for an explanation of how it works, you may look at DBI Recipes.