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

问题描述 投票:1回答:2

我需要测试我的SQLite数据库的结构,该数据库由一个唯一的表组成,例如2列(id,name)。我无法弄清楚SQL查询来获取我的数据库的表模式。

我可以使用DBI方法selectall_arrayref()获取数据库的所有内容。但是它只返回一个包含数据库中值的数组。这个信息很有用,但是我想要一个返回类似id, name(基本上是表模式)的SQL查询。

我尝试了以下查询:SHOW COLUMNS FROM $tablenameSELECT * from $tablename(这个返回所有表格内容)。

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

# 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();

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

我找不到好的查询。任何评论或帮助将不胜感激。

谢谢 !

database sqlite perl dbi
2个回答
2
投票

您正在寻找的只是表和列信息的SQL lite查询。这个答案SQLite Schema Information Metadata有完整的细节,如果这个查询不适合你,但假设你正在使用其中一个答案中提到的“最近”版本,你可以做这样的事情:

# 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";
}

1
投票

在深入了解社区答案后,我终于找到了使用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;
}

它返回表execution_host中存在的列名列表。

谢谢您的帮助 !

© www.soinside.com 2019 - 2024. All rights reserved.