My problem is that: the outputs are different, when I run the program on the linux machine, and on a web browser of another machine.
When I run the program on the linux machine, the output is:
Content-type: text/plain
11
22
username password
But when I put the program on an Apache Server, and access it using a browser on another machine, the output is simply:
11
It is probably because the program fails to connect to the database file. As I have set all the files to mode 777, that I do not have the permission is unlikely a reason.
Anyone know what the problem is and how to fix it?
#!/usr/bin/perl -w
use DBI;
print ("Content-type: text/plain\n\n");
print "11\n";
my $dbh = DBI->connect("dbi:SQLite:dbname=4140.db","","",{RaiseError => 1},) or die $DBI::errstr;
print "22\n";
my $sth = $dbh -> prepare("SELECT * FROM Credential");
$sth -> execute();
($usrname, $password) = $sth -> fetchrow();
$sth -> finish();
$dbh->disconnect();
print "$usrname $password\n";
The die strings are sent to STDERR and so won't appear in the HTTP message that is sent. You can solve this several ways, one of the simplest being to write an error handler for DBI errors that prints the error message to STDOUT.
You should also always use strict and use warnings. That way Perl will highlight many simple errors that you could otherwise easily overlook. use warnings is far superior to -w on the command line.
Take a look at this code as an example. Note that if you enable RaiseError as well as providing an error handler then DBI will raise an exception only if your error handler returns a false value.
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
print ("Content-type: text/plain\n\n");
print "11\n";
my $dbh = DBI->connect('dbi:SQLite:dbname=4140.db','','',
{RaiseError => 1, PrintError => 0, HandleError => \&handle_error});
print "22\n";
my $sth = $dbh->prepare('SELECT * FROM Credential');
$sth->execute;
my ($usrname, $password) = $sth -> fetchrow();
print "$usrname $password\n";
sub handle_error {
my ($msg, $dbh, $rv) = #_;
print "DB Error: $msg\n";
0;
}
Yo should specify the complete path to your database file in order to avoid this kind of problems. Try this (if your database is at the same path as your script):
use FindBin '$Bin';
my $dbfile = "$Bin/4140.db";
my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","",{RaiseError => 1},) or die $DBI::errstr;
#...
Check your error log. You'll surely find that SQLite is failing to create 4140.db because of a permission error. You've made incorrect assumptions about the current directory.
Related
I am trying to connect to Hive via Perl module Thrift::API::HiveClient and below is the code to connect to Hadoop hive and retrieve the data
#!/usr/bin/perl
use DBI;
use DBI::DBD;
use Data::Dumper;
use List::MoreUtils qw(uniq);
use DateTime;
#use warnings 'all';
use POSIX qw(strftime);
use LWP::Simple;
use Thrift;
use Thrift::API::HiveClient;
use Data::Dumper;
my $latest_return;
# Database connection
my $client = Thrift::API::HiveClient->new(
host => 'localhost',
port => '10000',
);
$client->connect or die "Could not connect";
my $rh = $client->execute('select * from devtest.users');
my $return = [];
while ($latest_return = $client->fetch($rh)) { # will die with an error if it fails
print $latest_return;
}
When I execute the above script it throws below message
Thrift::TException=HASH(0x25d18e0)
I also tried Dumper to print the result nothing got printed.
any help is much appreciated.
OK, so the problem here is - you're doing something that's failing.
The module you import - Thrift::API::Hiveclient warns:
THIS CODE IS ALPHA-QUALITY, EXPERIMENTAL, AND LIKELY FLAMMABLE
Having said that - what is happening here, is for some the action is failing, and it's dieing with an error object.
That error object has status code and message with it. (I don't think this is idomatic perl though, it's more like Java :)).
So in the connect there's an error, that's not being handled properly so your code is dying.
A Thrift::TException is a fairly simple sort of object:
package Thrift::TException;
sub new {
my $classname = shift;
my $self = {message => shift, code => shift || 0};
return bless($self,$classname);
}
1;
Literally just a message and a code.
To get at that message, you'll need to dereference your object, and that's what doesn't seem to be happening.
My best guess is the _open method in Thrift::Socket is returning an error, and the HiveClient isn't actually trapping/handling it.
It should be doing an eval and trapping the error, and then unpacking the TException.
Somewhere here:
sub connect {
my ($self) = #_;
$self->_transport->open;
}
Maybe. I'm not 100% sure, because Moo might do something cute with die, but I can't find or see where that is.
So short answer - you're probably failing to connect, to be sure you'd need to grab that error message - to do that you'll need to hack the Hiveclient to eval the operation. This is what you signed up for by using a module that's "Alpha quality".
I am new in perl, and I need to connect the database use DBI. My code as follows:
use LWP::Simple;
use XML::Simple qw(:strict);
use Data::Dumper;
use DBI;
use Getopt::Long;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
use IO::File;
use warnings;
$dbh = DBI->connect("dbi:);
if (!$dbh) {
&logMsg(0, "$DBI::errstr");
die;
} else {&logMsg(0,"Connection to $dbName DB OK")}
I already set the values. Its kind like connection failed, but I didn't get any errors. I also check the log file, there is nothing showing. What can I do for checking the errors? Thanks for any comments and help.
I can't find anything wrong with your code, unless logMsg just doesn't work, but it's a tedious way to go about using DBI.
Rather than checking if something went wrong with DBI, it's much better to set DBI to throw an error. You can do this with RaiseError.
my $dbh = DBI->connect(
"dbi:ODBC:DSN=$dbName;Server=$dbHost",
$dbUser, $dbPassword,
{ RaiseError => 1 }
);
Now if DBI has a failure, including trying to connect, it will throw an error and stop the program. This avoids having to check for an error every time you use the database (you'll forget).
DBI;
$dbh = DBI->connect('Your_Database_Name', 'user_id','Password');
my $sth = $dbh->prepare ("select * from Table_name");
$sth->execute();
my #row_ary = $sth->hetshrow_array;
foreach $item (#row_ary)
{
print "$item\n";
}
print syntax not working after my $dbh = DBI->connect($dsn, "username", "password"); has been called. But when I put print syntax on the top of my $dbh = DBI->connect($dsn, "username", "password"); print work properly. This case happen when I run this code through browser using CGI and when I run this code in command-line both work properly.
Here are the code:
#!"C:\Strawberry\perl\bin\perl.exe"
use CGI qw(:standard);
use DBI;
use JSON;
print header("application/json");
my $dsn = "DBI:mysql:database=webservices;host=localhost;port=3306";
print "test"; #work properly
my $dbh = DBI->connect($dsn, "root", "bukanjombloboy");
print "test"; #not working
my $result = $dbh->prepare("SELECT * FROM news");
$result->execute();
my $json_text = to_json($result->fetchall_arrayref());
print $json_text;
$dbh->disconnect();
Sorry for my bad English, thanks anyway.
It could be a issue with the EOL, in the line:
my $dbh = DBI->connect ($dsn, "root", "bukanjombloboy");
Check all your EOL are equal in all lines.
I have found the solution.
The problem is APACHE webserver doesn't have permission to access the library so I have to run XAMPP on administrator mode.
I have a database query that I am running inside an eval, to trap the error. Problem is that the error message is outputting to console, even though it is being trapped. How do I stop the error message from doing this, as I want to parse it myself and spit back my own messages?
my $dbh = DBI->connect('dbi:Pg:dbname=database;host=localhost',
'user', 'pass',
{RaiseError => 1}
);
eval{
$sth = $dbh->prepare($sql);
$sth->execute;
};
if($#){
#Do my parse/print stuff here I know
}
It's not a good idea to trap and ignore errors, whether they are fatal or not. Also, it is not advisable to check $# in the way you are doing it (see the questions on this site about perl exceptions for better ways to trap exceptions; I use Try::Tiny below, which is arguably the lightest-weight route of all).
Instead of proceeding with a DBI operation when an earlier one might have failed, you should check error conditions at every step:
use strict; use warnings;
use Try::Tiny;
try {
my $sth = $dbh->prepare($sql) or die $dbh->errstr;
$sth->execute or die $sth->errstr;
} catch {
print "got error $_\n";
# return from function, or do something else to handle error
};
And remember, always use strict; use warnings; in every module and script. Your code excerpt suggests that you are not yet doing this.
You can specify 'PrintError => 0' in your connect call (or use HandleError):
my $dbh = DBI->connect('dbi:Pg:dbname=database;host=localhost', $user, $passwd, {
PrintError => 0,
RaiseError => 1,
});
Or to set per statement handle:
my $sth = $dbh->prepare("SELECT * from my_table");
$sth->{PrintError} = 0;
$sth->execute();
...etc.
Also, don't depend on $# for indicating an error. A better way to use eval is:
my $result = eval {
...
$sth->...etc.
1;
}
unless ($result) {
# Do error handling..log/print $#
}
eval { } will trap a fatal error (from a die or Carp::croak call), but not a non-fatal error message (from warn or carp). To handle warning messages, see how to install a warning handler in documentation for %SIG or warn.
A trivial workaround is to use a trivial warning handler inside your eval block.
eval {
local $SIG{__WARN__} = sub { };
...
};
See also: perlfaq7: How do I temporarily block warnings?
I have a problem when I use Apache::DBI in child processes. The problem is that Apache::DBI provides a single handle for all processes which use it, so I get
DBD::mysql::db selectall_arrayref
failed: Commands out of sync; you
can't run this command now at
/usr/local/www/apache22/data/test-fork.cgi
line 20.
Reconnection doesn't help, since Apache::DBI reconnects in all processes, as I understood the following error
The server encountered an internal
error and was unable to complete your
request.
Error message: DBD driver has not
implemented the AutoCommit attribute
at
/usr/local/lib/perl5/site_perl/5.8.9/Apache/DBI.pm
line 283. ,
Here's the origin code:
use Data::Dumper 'Dumper';
use DBI ();
my $dbh = DBI->connect($dsn, $username, $password, {
RaiseError => 1,
PrintError => 0,
});
my $file = "/tmp/test-fork.tmp";
my $pid = fork;
defined $pid or die "fork: $!";
if ($pid) {
my $rows = eval { $dbh->selectall_arrayref('SELECT SLEEP(1)') };
print "Content-Type: text/plain\n\n";
print $rows ? "parent: " . Dumper($rows) : $#;
}
else {
my $rows = eval { $dbh->selectall_arrayref('SELECT SLEEP(1)') };
open FH, '>', $file or die "$file: $!";
print FH $rows ? "child: " . Dumper($rows) : $#;
close FH;
}
The code I used for reconnection:
...
else {
$dbh->disconnect;
$dbh = DBI->connect($dsn, $username, $password, $attrs);
my $rows = eval { $dbh->selectall_arrayref('SELECT SLEEP(1)') };
open FH, '>', $file or die "$file: $!";
print FH $rows ? "child: " . Dumper($rows) : $#;
close FH;
}
Is there a safe way to use Apache::DBI with forking? Is there a way to make it create a new connection perhaps?
I see a few options:
Explicitly close your DB handles when you fork, and reopen them as needed.
e.g.:
my $dbh = DBI->connect(...);
my $pid = fork;
defined $pid or die "fork: $!";
if ($pid) {
# parent...
}
else {
# child...
undef $dbh;
This could be made easier by storing the $dbh in an object, and passing around that object as needed to parts of your system. The object would be responsible for reopening the $dbh as needed, so the rest of the application doesn't have to concern itself with the details. Keep code encapsulated and well-separated from other parts of the system.
Don't use Apache::DBI. I can highly recommend DBIx::Connector, which opens a new connection as needed and doesn't preserve the bad behaviour of either plain DBI or Apache::DBI: see http://search.cpan.org/~dwheeler/DBIx-Connector-0.32/lib/DBIx/Connector.pm#Description for a detailed description of how it differs.
I use DBIx::Connector in my system inside a Moose object, which uses a method delegation to provide the dbh. The application simply does:
my $dbh = $db_dbj->dbh;
my $sth = $dbh->prepare(...);
# more boring DBI code here
...And the dbh is reconnected/regenerated as needed, invisibly.
As an aside, you should be really careful of using bare filehandles in a multiprocess environment. You could be very easily clobbering your data. open (my $fh, $file) or die "Cannot open $file: $!" is much safer.
I'm also a little nervous by seeing you using eval {} blocks without checking the contents of $#. You're just masking errors, rather than dealing with them, so there may be more things going on than you are aware of. Check your result values (or better, use an explicit exception-handling module, such as Try::Tiny. use use strict; use warnings;.
PS. I just noticed that you are explicitly including DBI in your code. Don't do that. If you use Apache::DBI in your startup_modperl.pl (or whatever you call your bootstrap file), you should never have to include DBI itself. I can't say for sure but I wouldn't be confident the right package is getting called (it's been a while since I looked at Apache::DBI's guts; it might take care of this for you though).
Don't fork under mod_perl2. Use Apache2::Subprocess. See also Is it a bad idea to fork under mod_perl2?