gpt4 book ai didi

mysql - Perl和MySQL用户输入选择一行?

转载 作者:行者123 更新时间:2023-11-29 12:23:19 25 4
gpt4 key购买 nike

假设我有一个简单的数据库表,没有 ID_KEY 但有名称列。我想像这样显示输出

+----+---------+
| | name |
+----+---------+
| 1 | dog |
| 2 | cat |
| 3 | penguin |
| 4 | lax |
| 5 | whale |
| 6 | ostrich |
+----+---------+

然后有一个<STDIN>例如,3 选择企鹅。 3 只是您执行 select 调用时出现的行号。

有什么方法可以做到这一点,还是只能通过关联的 id 键然后使用与该 id 键匹配的后续 select 语句来实现?

最佳答案

一开始我误解了你的意思,但后来我明白了。但这没有多大意义,因为当您在 Perl 程序中输入数字时,您将不会使用 MySQL 命令行工具,并且无法看到要输入哪些数字..

您需要做的是编写 Perl 程序,以便它打印表中的所有 name 字段以及行号。然后您的程序可以将输入的动物编号翻译为其名称,因为它知道打印的内容。

像这样的东西会起作用。当然,您必须正确设置名称、IP 地址和凭据,以便 DBI 可以连接到数据库。

use strict;
use warnings;

use DBI;

my $dbh = DBI->connect(
'DBI:mysql:database=animal_test',
'username',
'password',
{ RaiseError => 1 },
);

my $names = map @$_, $dbh->selectall_arrayref('SELECT name FROM animals');
for my $i ( 0 .. $#$names ) {
printf "%3d: %s\n", $i+1, $names->[$i];
}
print "\n";

print "Enter animal number: ";
my $animal = <>;
chomp $animal;

my $name = $names->[$animal-1];

printf "Animal chosen is %s\n", $name;

关于mysql - Perl和MySQL用户输入选择一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28708206/

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