gpt4 book ai didi

sql - 将 psql 查询从 perl 传递到字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:11 25 4
gpt4 key购买 nike

目前我有一个 perl 脚本可以访问我们的数据库,执行某些查询并将输出打印到终端。相反,我想在生成 pdf 之前将结果输出到模板 latex 文件中。对于我的大多数查询,我提取数字并将它们存储为标量变量(例如,特定运算符(operator)执行给定任务的频率)。例如。

foreach $op (@operator) {
$query = "SELECT count(task_name) FROM table WHERE date <= '$date_stop' and
date >= '$date_start' and task=\'$operator[$index]\';";

#execute query
$result=$conn->exec($query);
$conres = $conn->errorMessage;
if ($result->resultStatus eq PGRES_TUPLES_OK) {
if($result->ntuples > 0) {
($task[$index]) = $result->fetchrow;
}
printf("$operator[$index] carried out task: %d\n", $task[$index]);
} else {
die "Failed.\n$conres\n\n";
exit -1;
}
$index++;
}
printf("**********************************\n\n");

在最终报告中,我将在表格中总结每个运算符(operator)完成每个任务的次数。除此之外,还有一些必须报告的事件。我可以使用诸如

之类的命令轻松地将这些打印到终端
$query = "SELECT operator, incident_type from table_name WHERE incident_type = 'Y' 
and date <= '$date_stop' and date >= '$date_start';";
$result=$conn->exec($query);
$conres = $conn->errorMessage;
if ($result->resultStatus eq PGRES_TUPLES_OK) {
if($result->ntuples > 0) {
$result->print(STDOUT, 1, 1, 0, 0, 0, 1, "\t", "", "");
}
} else {
die "Failed.\n$conres\n\n";
exit -1;
}

此命令的输出示例是

operator  |   incident_type
-----------------------------
AB | Incomplete due to staff shortages
-------------------------------
CD | Closed due to weather
-----------------------------

如何让我的 perl 脚本将运算符名称和事件传递到字符串数组中,而不是仅仅将结果发送到终端?

最佳答案

您应该考虑更新脚本以使用 DBI .这是 Perl 中数据库连接的标准。

DBI 具有将参数插入查询字符串的内置工具。它比自己手动创建字符串更安全、更快捷。在循环之前,执行一次:

#dbh is a database handle that you have already opened.
my $query = $dbh->prepare(
"SELECT count(task_name) FROM table WHERE date<=? and date>=? and task=?"
);

然后在循环中,你每次只需要这样做:

$query->execute($date_stop,$date_start,$op);

请注意,您传递给 execute 的参数会自动插入到语句中的 ? 位置。它会为您处理报价。

同样在循环中,执行语句后,可以得到这样的结果:

my $array_ref = $query->fetchall_array_ref;

现在所有的行都存储在一个二维数组结构中。 $array_ref->[0][0] 将返回第一行的第一列。

参见 DBI documentation获取更多信息。

正如其他人所提到的,您的代码中还有很多其他错误。确保以 use strict; 开头。使用警告;,如果您需要进一步的帮助,请提出更多问题!

关于sql - 将 psql 查询从 perl 传递到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14339100/

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