【问题标题】:DBI: alter table - questionDBI:更改表 - 问题
【发布时间】:2011-03-14 10:49:56
【问题描述】:
#!/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

【问题讨论】:

    标签: perl dbi alter-table


    【解决方案1】:

    分两步进行:

    Create the 3 columns
    insert data in them 
    

    【讨论】:

      【解决方案2】:

      您准备了 3 次 SQL 语句并为值 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 } );
      

      【讨论】:

        猜你喜欢
        • 2012-03-22
        • 1970-01-01
        • 1970-01-01
        • 2011-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-07
        相关资源
        最近更新 更多