perl DBI: populate a scalar from a select statement

hi

every resource i see regarding DBI refers to retrieving data from a database into and array or a hash, but i havent seen anything on how to pull out a single value to a scalar

in my database i have a field called "forcewrite" with a value of "6". I am trying to connect to the database, pull this value straight out to a scalar variable, so i can evaluate it later... is there a way to do this ..?

I tried this but this just returns a value of "1" everytime i run it (im assuming it must be an error code or something because im not sure where its getting the "1" from)

#!/usr/bin/perl -w
use DBI;
my $primac = "6666.5555.4444";
my $dbh = DBI->connect("DBI:mysql:myDB","username","password",) or die $DBI::errstr;
my $force = $dbh->do("SELECT forcewrite FROM table WHERE primac = '$primac'") or die $DBI::errstr;
print "$force\n";

Is there a way to pull a value from a DB straight into a scalar ?

---------- Post updated at 08:17 PM ---------- Previous update was at 08:06 PM ----------

ive managed to get it working this way ...just would be nice if i could go straight to a scalar as opposed to the first element of an array... oh well

#!/usr/bin/perl -w
use DBI;
my $primac = "6666.5555.4444";
my $dbh = DBI->connect("DBI:mysql:myDB","username","password",) or die $DBI::errstr;
my $sth = $dbh->prepare("SELECT forcewrite FROM admin WHERE primac = '$primac'") or die $DBI::errstr;
$sth->execute() or die  $DBI::errstr;
my $force = ($sth->fetchrow_array())[0];
print "$force\n";

Try this:

my $force;

my $dbh = DBI->connect("DBI:mysql:myDB","username","password",) or die $DBI::errstr;

my $sth = $dbh->prepare("SELECT forcewrite FROM table WHERE primac = '$primac") || die "Error parsing SQL: $DBI::errstr\n";

$sth->execute() || die "Error executing SQL: $DBI::errstr\n";

$sth->bind_col(1, \$force  ) || die "Error binding variable: $DBI::errstr\n";

while ( $sth->fetch ) {
    print "force = $force\n";
}
$
$ mysql -u test -ptest -e "select nic from t where ip = '3.3.3.3'" test
+------+
| nic  |
+------+
| CE0  |
+------+
$
$ cat -n fetchone.pl
     1  #!/usr/bin/perl -w
     2  use DBI;
     3  $dbh = DBI->connect('dbi:mysql:test','test','test');
     4  my $nic = $dbh->selectrow_array("select nic from t where ip = '3.3.3.3'");
     5  print "nic = $nic\n";
     6
$
$ perl fetchone.pl
nic = CE0
$
$

tyler_durden