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

Hi guys , im trying to declare an 'insert into' statement for a prepare function using a place holder for the table name but ... can not get it to work, the idea is as follows:

$sth = $dbh->prepare("INSERT INTO ? (ip,bsid,firmware) VALUES (?, ?, ? +)"); $sth->execute($table_name,$ip,$bsid,$firmware);

but im getting:

DBD::mysql::st execute failed: called with 4 bind variables when 3 are + needed

Replies are listed 'Best First'.
Re: perl dbi, prepare function using place holder
by Marshall (Canon) on Aug 25, 2016 at 16:17 UTC
    As far as I know, a prepare statement is going to be specific for a table (how many and what indices it has etc). So, you could:
    my $table_name = 'Table'; $sth = $dbh->prepare("INSERT INTO $table_name (ip,bsid,firmware) VALUE +S (?, ?, ?)"); $sth->execute($ip,$bsid,$firmware);
    If you want to change tables, you have to "prepare" again with that specific table name.

      a prepare statement is going to be specific for a table

      Yeah, ? can be used for values, not objects.

        Yes. The prepare statement can potentially do a lot of work figuring out how to actually perform the SQL statement in the most efficient manner. Even in this simple INSERT example, say Table1 has an index based upon "ip" and Table2 doesn't or is indexed in some other way. The insert for Table1 requires a different set of functionality (also update the index) than for Table2. Using a different Table is a lot more involved than generically inserting different column values. A fancy SELECT statement could have vastly differing execution strategies depending upon exactly what table(s) it is operating upon. Essentially there are limits to what the DB can be "prepared" in advance to handle.