【问题标题】:Perl - Get the structure of a sqlite database using DBIPerl - 使用 DBI 获取 sqlite 数据库的结构
【发布时间】:2019-08-19 08:05:39
【问题描述】:

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

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

我尝试了以下查询:SHOW COLUMNS FROM $tablename,但也尝试了SELECT * 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

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

谢谢!

【问题讨论】:

标签: database sqlite perl dbi


【解决方案1】:

您要查找的实际上只是针对表和列信息的 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";
}

【讨论】:

    【解决方案2】:

    在挖掘社区答案后,我终于找到了使用 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 中存在的列名称的列表。

    感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 2014-12-20
      相关资源
      最近更新 更多