Perl 为SQL查询的结果指定标量
在我看来,必须有一个更好的方法来做到这一点,但我仍然没有找到一个。我相信我不是唯一一个可以使用这种方法的人:运行一个SQL查询,在一行中只生成一个字段,然后将该字段分配给标量。(在我的例子中,如果查询结果包含多个字段/行,那么我需要担心的事情比脚本破坏更大) 例如,要从SQL server获取时间戳,可以使用:Perl 为SQL查询的结果指定标量,perl,postgresql,dbi,Perl,Postgresql,Dbi,在我看来,必须有一个更好的方法来做到这一点,但我仍然没有找到一个。我相信我不是唯一一个可以使用这种方法的人:运行一个SQL查询,在一行中只生成一个字段,然后将该字段分配给标量。(在我的例子中,如果查询结果包含多个字段/行,那么我需要担心的事情比脚本破坏更大) 例如,要从SQL server获取时间戳,可以使用: my $timestamp; my $cmd = $dbh->prepare('SELECT cast(now() AS timestamp);') or die $!; $cmd
my $timestamp;
my $cmd = $dbh->prepare('SELECT cast(now() AS timestamp);') or die $!;
$cmd->execute();
while (my @asd = $cmd->fetchrow_array) { $timestamp = $asd[0] }
很脏,但能用。但是对于一个简单的赋值来说,使用4行似乎有点过分,特别是考虑到perl和postgresql通过DBI相互通信的能力。当然,我可以为它编写一个子例程,但是是否有一些本机程序可以让我像使用$dbh->do()
提交数据一样轻松地获取数据
是的,我尝试过谷歌。不会因为你只需要一列而只返回一个标量吗?不会因为你只需要一列而只返回一个标量吗?总会有: 选择行数组 此实用程序方法将
prepare
、execute
和fetchrow\u array
组合到一个调用中
比如说:
my $timestamp = $dbh->selectrow_array('select cast(now() as timestamp)');
对于类似的情况,还有和。总是有:
选择行数组
此实用程序方法将prepare
、execute
和fetchrow\u array
组合到一个调用中
比如说:
my $timestamp = $dbh->selectrow_array('select cast(now() as timestamp)');
对于类似的情况,还有和。来自
perldoc DBI
:
"selectrow_arrayref"
$ary_ref = $dbh->selectrow_arrayref($statement);
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
This utility method combines "prepare", "execute" and
"fetchrow_arrayref" into a single call. It returns the first row of
data from the statement. The $statement parameter can be a previously
prepared statement handle, in which case the "prepare" is skipped.
If any method fails, and "RaiseError" is not set, "selectrow_array"
will return undef.
这会让你走完大部分路。您仍然需要执行一些错误检查,但无论如何都要执行。来自
perldoc DBI
:
"selectrow_arrayref"
$ary_ref = $dbh->selectrow_arrayref($statement);
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
This utility method combines "prepare", "execute" and
"fetchrow_arrayref" into a single call. It returns the first row of
data from the statement. The $statement parameter can be a previously
prepared statement handle, in which case the "prepare" is skipped.
If any method fails, and "RaiseError" is not set, "selectrow_array"
will return undef.
这会让你走完大部分路。您仍然需要进行一些错误检查,但无论如何您都会这样做。通常我写:
$value = $dbh->selectall_arrayref($sql)->[0]->[0];
我通常写:
$value = $dbh->selectall_arrayref($sql)->[0]->[0];
是的,但它仍然需要事先准备/执行一对。是的,但它仍然需要事先准备/执行一对。工作起来很有魅力!如果意外返回了多个,那么也有默认到第一行的优点。对不起,是的,我是说第一行。经过相应的编辑,现在我要喝早茶了。效果很好!如果意外返回了多个,那么也有默认到第一行的优点。对不起,是的,我是说第一行。编辑好了,现在我要喝早茶了。