Perl DBI::SQLite:如何转储具有列名的表?

U. *_*ndl 2 sqlite perl dbi

类似于如何获取Sqlite3数据库上的列名列表?,但仍然不同:

出于调试目的,我编写了一个转储 SQLite3 表的闭包。输出不是很漂亮,但它可以工作:

sub something($)
{
    my $dbh = shift;
    my $me = '_dump_tables';
    my $sep = '-' x length($me);
    my $dump_table = sub ($) {          # dump specified table or view
        if (defined(my $rows = $dbh->selectall_arrayref(
                        "SELECT * FROM $_[0]"))) {
            my $nsep = '-' x length($_[0]);

            print "$me: $_[0]\n";
            print "${sep}--${nsep}\n";
            foreach (@$rows) {
                print join('|', map { $_ // 'NULL' } @$_), "\n";
            }
        } else {
            print "$me: Houston, we have a problem! ;-)\n";
        }
    };

    #...
    $dump_table->('table_name');
    #...
}
Run Code Online (Sandbox Code Playgroud)

输出可能如下所示:

_dump_tables: EXAMPLE
---------------------
1|D1|K1
2|D2|K2
3|D3|K3
4|D4|K4
5|D5|K5
6|D6|K6
Run Code Online (Sandbox Code Playgroud)

我想将列名称添加为第一行,寻找一个最好简单的解决方案。

一些细节

EXAMPLE表可以被认为是:

CREATE TABLE EXAMPLE (
ID      INTEGER PRIMARY KEY NOT NULL
A       VARCHAR(128) NOT NULL,
B       VARCHAR(128) NOT NULL
);
INSERT INTO EXAMPLE (A, B)
VALUES ('D1', 'K1'), ('D2', 'K2'), ('D3', 'K3'),
       ('D4', 'K4'), ('D5', 'K5'), ('D6', 'K6');
Run Code Online (Sandbox Code Playgroud)

注意:由于某种原因,即使ID没有AUTOINCREMENT.

cho*_*oba 5

您可以使用该NAME方法,但需要将 拆分selectallprepareexecutefetchall让语句句柄来调用它:

        my $select = $dbh->prepare("SELECT * FROM $_[0]");
        $select->execute;
        if (defined(my $rows = $select->fetchall_arrayref)) {

            my $nsep = '-' x length($_[0]);

            print "$me: $_[0]\n";
            print "${sep}--${nsep}\n";
            my $header = $select->{NAME};
            foreach ($header, @$rows) {
                print join('|', map { $_ // 'NULL' } @$_), "\n";
            }
Run Code Online (Sandbox Code Playgroud)

column_info或者直接在数据库上使用该方法。这不太通用,因为它仅适用于SELECT *.

    my $dump_table = sub ($) {          # dump specified table or view
        if (defined(my $rows = $dbh->selectall_arrayref(
                        "SELECT * FROM $_[0]"))) {

            my @colnames;
            my $info = $dbh->column_info(undef, undef, $_[0], '%');
            while (my $col = $info->fetchrow_arrayref) {
                # COLUMN_NAME is at index 3 (4th field)
                unshift @colnames, $col->[3];
            }

            my $nsep = '-' x length($_[0]);

            print "$me: $_[0]\n";
            print "${sep}--${nsep}\n";
            foreach (\@colnames, @$rows) {
                print join('|', map { $_ // 'NULL' } @$_), "\n";
            }
Run Code Online (Sandbox Code Playgroud)