Sandra Schlichting
Sandra Schlichting

Reputation: 25986

How do I get the results of a MySQL query from Perl's DBI?

I am doing the following, and getting "1" which I assume means the statement wend well. But I would like the result instead.

What's wrong?

#!/usr/bin/perl

use strict;
use DBI;

my $host = "test";
my $database = "dd";
my $port = 3306;
my $user = "uuu";
my $pw = "ppp";

my $mysql = DBI->connect("DBI:mysql:database=$database;host=$host;port=$port", $user, $pw)
    or die "Cannot connect to MySQL server\n";

my $m = $mysql->do(qq{select MAX(idvisit) from log_visit});

print $m;

Upvotes: 3

Views: 3854

Answers (4)

mscha
mscha

Reputation: 6830

my $m = $mysql->selectrow_array(qq{select MAX(idvisit) from log_visit});

Upvotes: 1

Dave Cross
Dave Cross

Reputation: 69224

It's always worth checking the documentation for functions that you're having trouble with.

In this case the DBI documentation for "do" says:

Prepare and execute a single statement. Returns the number of rows affected or undef on error.

And, more explicitly,

It should not be used for SELECT statements because it does not return a statement handle (so you can't fetch any data).

Upvotes: 8

Femaref
Femaref

Reputation: 61427

do returns the number of affected rows. You might want to look into the statement class and specifically, the execute function.

Upvotes: 3

Sandra Schlichting
Sandra Schlichting

Reputation: 25986

my $m = $mysql->prepare("select MAX(idvisit) from log_visit");
$m->execute() or die "Couldn't execute statement: ".$m->errstr;
print $m->fetch()->[0];

Upvotes: 8

Related Questions