Perl - 使用 DBI 获取 sqlite 数据库的结构

Perl - Get the structure of a sqlite database using DBI

我需要测试我的 SQLite 数据库的结构,该数据库由一个唯一的 table 组成,假设有 2 列(id、名称)。我无法弄清楚 SQL 查询来获取我的数据库的 table 模式。

我可以使用 DBI 方法获取数据库的所有内容 selectall_arrayref()。但是它只是 returns 一个包含我数据库中的值的数组。此信息很有用,但我想要一个 SQL 查询,其中 returns 类似于 id, name(基本上,table 架构)。

我尝试了以下查询:SHOW COLUMNS FROM $tablename 还有 SELECT * from $tablename(这个 returns 所有 table 内容)。

到目前为止,这是我的实现:

# database path
my $db_path   = "/my/path/to/.database.sqlite";
my $tablename = "table_name";

sub connect_to_database {

    # Connect to the database
    my $dbh = DBI->connect ("dbi:SQLite:dbname=$db_path", "", "",
                            { RaiseError => 1, AutoCommit => 0 },
                           )
    or confess $DBI::errstr;
    return $dbh;
}

sub get_database_structure {

    # Connect to the database
    my $dbh = &connect_to_database();

    # Get the structure of the database
    my $sth = $dbh->prepare("SHOW COLUMNS FROM $tablename");
    $sth->execute();
    while (my $inphash = $sth->fetrow_hashref()) {
        print $inphash."\n";
    }

    # Disconnect from the database
    $dbh->disconnect();
}

# Call the sub to print the database structure
&get_database_structure();

我希望输出是我的 table 的结构,所以 id, name 但我提出了一个错误:DBD::SQLite::db prepare failed: near "SHOW": syntax error

我找不到合适的查询。任何意见或帮助将不胜感激。

谢谢!

您正在寻找的实际上只是 SQL 对 table 和列信息的精简查询。如果此查询对您不起作用,则此答案 SQLite Schema Information Metadata 包含完整的详细信息,但假设您使用的是答案之一中提到的任何 'recent' 版本,您可以执行类似这个:

# Get the structure of the database
my $sth = $dbh->prepare("<<END_SQL");
SELECT 
  m.name as table_name, 
  p.name as column_name
FROM sqlite_master AS m
JOIN pragma_table_info(m.name) AS p
ORDER BY m.name, p.cid
END_SQL
$sth->execute();
my $last = '';
while (my $row = $sth->fetchrow_arrayref()) {
    my ($table, $column) = @$row;
    if ($table ne $last) {
        print "=== $table ===\n";
        $last = $table;
    }
    print "$column\n";
}

在深入研究社区答案后,我终于找到了使用 pragma table_info 的解决方案。

sub get_database_structure {

    # Connect to the database
    my $dbh = &connect_to_database ();

    # Return the structure of the table execution_host
    my $sth = $dbh->prepare('pragma table_info(execution_host)');
    $sth->execute();
    my @struct;
    while (my $row = $sth->fetchrow_arrayref()) {
        push @struct, @$row[1];
    }

    # Disconnect from the database
    $dbh->disconnect ();

    return @struct;
}

它 returns table execution_host 中存在的列名列表。

感谢您的帮助!