views:

78

answers:

2

Hi, Could you plesae teach me how to Loop & rename MySQL table in Perl. Thanks.

my code snippet attached

use strict; 
use warnings; 
use DBI; 

my $dbh = DBI->connect( 
    'DBI:mysql:database=dbdev;host=localhost', 
    'dbdev', 
    'dbdevpw', 
    { RaiseError => 1, AutoCommit => 1 }, 
); 

my $sql = RENAME TABLE old_table TO new_table; 
my $sth = $dbh->prepare($sql); 

while (<DATA>){ 
    chomp; 
    // How to implement the Rename all the old tables with the while loop.


    $sth->execute(); 
} 
+2  A: 

This code can be used to rename all tables in the database:

my @tables = map @$_, @{ $dbh->selectall_arrayref('SHOW TABLES') };

for my $table (@tables) {
    $dbh->do("RENAME TABLE $table TO new_${table}");
}

Hope this helps.

eugene y
+2  A: 

I'm assuming your list of tables live in DATA.

while (<DATA>){ 
    chomp; 
     $dbh->do("RENAME TABLE ? TO ?", undef, $_, "new_" . $_);
} 

You might also want to take a look at perldoc DBI

Logan
++ for placeholders.
daotoad
Please clarify. According to perldoc dbi it's ?
Logan