【发布时间】: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 或帮助将不胜感激。
谢谢!
【问题讨论】:
-
SHOW不是 sqlite-dialect SQL 命令。你想要table_info编译指示:sqlite.org/pragma.html#pragma_table_info -
您想要
CREATE语句,还是想要列标题? DBI 有一个内置的方法来从语句句柄中产生这些。 -
我想要列标题。
-
似乎metacpan.org/pod/DBI#NAME1 不是由 dbd::SQLite 实现的。使用时会显示“bright_yellow”。
-
我尝试使用 table_info 方法 (metacpan.org/pod/DBI#table_info) 但它没有返回我期望的结果。