gpt4 book ai didi

perl - 如何使用 Perl $dbh->tables 获取每个表的单行?

转载 作者:行者123 更新时间:2023-12-03 16:21:45 24 4
gpt4 key购买 nike

我想像 .schema 一样检索 sqlite 数据库模式信息,但使用 Perl DBI。第一次尝试是使用 $dbh->tables 检索表名。但我得到重复的表名。它们是表本身的一个条目和我拥有的每个索引的一个条目(table_a 有 3 个索引,b 有一个)这背后的基本原理是什么?

DB<7> x $dbh->tables;
0 '"main"."table_a"'
1 '"main"."table_a"'
2 '"main"."table_a"'
3 '"main"."table_b"'
4 '"main"."sqlite_master"'
5 '"temp"."sqlite_temp_master"'
6 '"main"."table_a"'
7 '"main"."table_b"'

我很感激有人可以为这三个相关问题提供提示:
如何只获取表(不做 uniq)以及为什么每个索引只有一行?
如何获取索引信息?
总而言之,如何获得.schema的等效信息?

[更新] 我在 DBI 1.627 看到过
@names = $dbh->tables;        # deprecated

但它没有提到原因。

他们建议使用
@names = $dbh->tables( $catalog, $schema, $table, $type );

但是在阅读了解释此参数的 DBI table_info 之后,我还没有完全理解如何填充它们以获取表的信息以仅获取表名一次,或者如果有可能获得所有表名,相同的信息使用 .schema。

任何示例或更详细用法的链接将不胜感激。

[[更新]]
仅供将来引用,这些是阻止我在此处提问之前自己找到答案的两个问题:

1- 谷歌将我​​引导到一个非常古老的 DBD-sqlite 文档页面,其中几乎没有任何内容,我没有注意页面顶部的最新版本的链接。

2- 在问这里之前,我在其他线程中阅读了有关 table_info (正确答案)的信息,但是几年没有编写 DBI 代码,我陷入了新手陷阱之一。由于 $dbh->tables 返回一个数组,我没有注意 table_info 返回一个语句处理程序,所以当尝试 x $dbh->table_info(...)在调试器中并获得了一个空哈希,我被卡住了。我忘记了将 fetch 部分调用到返回的 $sth 的需要。

最佳答案

How can obtain only the tables (without doing a uniq)


$dbh->tables接口(interface)太简单了,我猜,不能代表 SQL 引擎和各种驱动程序的复杂性。如您所见,您应该使用 table_info()反而。

具体见 DBD::SQLite documentation for table_info() (在撰写本文时为 v1.39),因为 DBD 文档可以告诉您数据库和驱动程序支持哪些功能(例如,SQLite 没有目录)。像这样的东西会给你你想要的:
use feature qw(say);
...

# Get info on every ('%') TABLE entity in the "main" schema. Catalog is blank
# b/c DBD::SQLite and/or SQLite itself has no concept of catalogs.
my $sth = $dbh->table_info('', 'main', '%', 'TABLE');

while (my $r = $sth->fetchrow_hashref) { # outputs: table_a
say $r->{TABLE_NAME}; # table_b
}

and why there is one row for each index?



不确定,但可能是 tables() 的意外简单的界面。再次使用 table_info()枚举表和类似表的对象。

How can I obtain the indexes info?



实验 statistics_info()方法可能受支持。

and all together, how to obtain the equivalent info of .schema?



你很幸运。 DBD::SQLite 驱动程序提供 table_info扩展字段 'sqlite_sql' ,对我来说,它给出了每个表后面的“CREATE TABLE ...”语句。 (也是我从 .schema 中得到的。)尝试:
my $sth = $dbh->table_info('', 'main', '%', 'TABLE');

while (my $r = $sth->fetchrow_hashref) {
say $r->{sqlite_sql};
}

关于perl - 如何使用 Perl $dbh->tables 获取每个表的单行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com