DBI:alter table - 问题

时间:2011-03-14 10:49:57

标签: perl dbi alter-table

#!/usr/bin/env perl
use warnings;
use 5.012;
use DBI;

my $dsn = "DBI:Proxy:hostname=horst;port=2000;dsn=DBI:ODBC:db1.mdb";
my $dbh = DBI->connect( $dsn, undef, undef ) or die $DBI::errstr;
$dbh->{RaiseError} = 1;
$dbh->{PrintError} = 0;

my $my_table = 'my_table';
eval{ $dbh->do( "DROP TABLE $my_table" ) };
$dbh->do( "CREATE TABLE $my_table" );

my $ref = [ qw( 1 2 ) ];

for my $col ( 'col_1', 'col_2', 'col_3' ) {
    my $add = "$col INT";
    $dbh->do( "ALTER TABLE $my_table ADD $add" );
    my $sql = "INSERT INTO $my_table ( $col ) VALUES( ? )";
    my $sth = $dbh->prepare( $sql );
    $sth->bind_param_array( 1, $ref );
    $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } );
}

my $sth = $dbh->prepare( "SELECT * FROM $my_table" );
$sth->execute();
$sth->dump_results();

$dbh->disconnect;

此脚本输出:

'1', undef, undef
'2', undef, undef
undef, '1', undef
undef, '2', undef
undef, undef, '1'
undef, undef, '2'
6 rows

如何更改此脚本以获取此输出:

'1', '1', '1'
'2', '2', '2'
2 rows

2 个答案:

答案 0 :(得分:1)

分两步完成:

Create the 3 columns
insert data in them 

答案 1 :(得分:1)

您准备一个SQL语句3次,并对值1,2执行两次,这样您就可以获得6行。我不知道如何回答你如何改变它以获得2行的问题,因为我们不知道你想要实现什么。在不知道你想要实现什么的情况下我会猜测,但以下结果会产生你想要的输出:

my $ref = [ qw( 1 2 ) ];

for my $col ( 'col_1', 'col_2', 'col_3' ) {
    my $add = "$col INT";
    $dbh->do( "ALTER TABLE $my_table ADD $add" );
}
$sql = "INSERT INTO $my_table ( col_1, col_2, col_3 ) VALUES( ?,?,? )";
my $sth = $dbh->prepare( $sql );
$sth->bind_param_array( 1, $ref );
$sth->bind_param_array( 2, $ref );
$sth->bind_param_array( 3, $ref );
$sth->execute_array( { ArrayTupleStatus => \my @tuple_status } );