使用Perl从数据库中获取一行

时间:2014-04-04 10:15:51

标签: perl postgresql

我正在尝试使用postgreSQL运行与Perl的简单数据库连接

use DBI;

$database = "postgres";
$user     = "postgres";
$password = "admin";

my $dbh = DBI->connect(  "dbi:Pg:dbname=$database"
                       , $user
                       , $password
                      )
or die "Can't Connect to database: $DBI::errstr\n";

# get data from the URL string
my $firstname = "haroon";
my $lastname ="ash";
my $age = 24;

# insert the data into the database
my $query = "INSERT INTO people (firstname, lastname, age) 
             VALUES ('$firstname','$lastname', '$age')";
$dbh->do($query);

# get the ID of the inserted person
$query = "SELECT MAX(id) FROM people";
my $sth = $dbh->prepare($query);
my $rv =$sth->execute;
if($rv < 0){
   print $DBI::errstr;
}
else {
   my $row = $sth->fetchrow_hashref; 
   my $person_id = $row->{'max'};
   print $firstname, $lastname 
       . "was successfully inserted at position " 
       . $person_id;
}

我正在尝试打印我最近输入的人物ID。但my $person_id = $row->{'max'}似乎给了我正确的答案,而不是my $person_id = $row->{'id'};。我不明白为什么会这样。

3 个答案:

答案 0 :(得分:1)

您可能希望为查询

设置列别名
$query = "SELECT MAX(id) AS id FROM people";

因为postgres正在给你自己的别名,那就是max

如果你想要的是最后插入的id,你可以

my $query = "INSERT INTO people (firstname, lastname, age) 
         VALUES (?,?,?)
         returning id
";

并像对待select一样获取查询。 (查看pg docs

答案 1 :(得分:0)

您没有在插入语句中输入PERSON_ID。

相反,似乎ID字段由DB填充,插入期间的自动增量值似乎。

在不知道表格定义(以及表格上可能的插入触发器)的情况下,很难/不可能给出更好的答案。

答案 2 :(得分:0)

您可以使用RETURNING关键字返回与您刚插入的行相关联的id

my $query = '
  INSERT INTO people (firstname, lastname, age)
  VALUES ($1, $2, $3)
  RETURNING id';
my $sth = $dbh->prepare($query);
$sth->execute($firstname, $lastname, $age);
my $rv = $sth->fetchrow_hashref();
printf "%s, %s was successfully inserted at position %d\n",
  $firstname, $lastname, $rv->{id};