2014-04-04 40 views
1

我試圖運行使用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用Perl一個簡單的數據庫連接擷取來自數​​據庫的一個單列。但my $person_id = $row->{'max'}似乎給我正確的答案,而不是my $person_id = $row->{'id'};。我不明白這是爲什麼。

+0

看看['爲postgresql' mysql_insert_id替代(HTTP://計算器.com/q/55956/1733163) – Miller

回答

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

+0

沒有佔位符? – ThisSuitIsBlackNot

+0

@ThisSuitIsBlack未注意到,這僅僅是來自OP的cp,但是在這裏你去了,更新了。 –

+1

你至少應該告訴他們他們在做什麼是一個壞主意,他們爲什麼應該使用佔位符。我可以在評論中做到這一點,但既然你已經給出了一個答案,顯示一個查詢,你也可以在OP上進行一點教育。 – ThisSuitIsBlackNot

0

您未在插入語句中輸入PERSON_ID。

相反,似乎ID字段由數據庫填充,插入期間自動增量值,似乎。

不知道表定義(和表上的潛在插入觸發器)很難/不可能給你一個更好的答案。

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};