unable to execute mysql query in perl while connecting to remote server - mysql

I have connected to one MySQL database which have been hosted in a remote server in Perl. Now I am trying to execute a select statement on a table in subject.pl file using Perl command line. The code is
#!/usr/bin/perl
use DBI;
use strict;
# Connected to mysql audit database in dev server
my $dsn = 'DBI:mysql:Driver={mysql}';
my $host = 'dev-mysql.learn.local';
my $database = 'subject';
my $user = 'testUser';
my $auth = 'testPassword';
my $dbh = DBI->connect("$dsn;host=$host;Database=$database",$user,$auth) or die "Database connection not made: $DBI::errstr";
# Prepare query
my $sql = "SELECT
subject_id
,subject_value
FROM
subject";
my $sth = $dbh->prepare($sql);
#Execute the statement
$sth->execute() or die "Unable to execute".$sth->errstr;
while (my #row = $sth->fetchrow_array()) {
my ($subject_id, $subject_value ) = #row;
print "$subject_id,$subject_value,$subject_db_field\n";
}
$sth->finish();
I am getting error at line $sth->execute() or die "Unable to execute".$sth->errstr;
The error message is Unable to execute at D:\Demo\perl_demo\subject.pl line 24.
But when I am printing the $dbh variable, its giving the result like DBI::db=HASH(0x1ca7884). So I guess the connection is establishing properly.
Please help me to fix this issue as I am completely new in Perl scripting.

Check for errors on prepare,
my $sth = $dbh->prepare($sql) or die $dbh->errstr;

Related

Perl DBI Can't work out what driver to use

So I am attempting to connect to a database on an end device from one of my servers, however I'm getting the following error:
Can't connect to data source '<user>' because I can't work out what driver to use (it doesn't seem to contain a 'dbi:driver:' prefix and the DBI_DRIVER env var is not set) at <script> line 18
My lines of code are the following. I removed some private information of course.
my $sHDS = shift || "<host>";
my #rows;
my $cust = '<customer name>';
my $dsn = 'dbi:Sybase:' . $sHDS;
my $user = '<user>';
my $pass = '<password>';
my $hDb = DBI::connect($dsn, $user, $pass)
or die "Can not connect to ICM Database $DBI::errstr";
Anyone see where I am going wrong?
The correct call has the format
DBI->connect($dsn, $user, $password)
which is subtly but significantly different from
DBI::connect($dsn, $user, $password)
The first call is equivalent to the call
DBI::connect( 'DBI', $dsn, $user, $password )
and the connect function in DBI actually expects your dsn to be specified in the 2nd argument it receives.

perl DBI execute statement for LOAD DATA INFILE

I am relatively new to perl and this forum. I am trying to use perl DBI for mySql LOAD DATA INFILE statement to upload a csv file to a mySQL database. However, the execute statement returns an undef value. However if i use a SELECT or DESC statement, it works fine. I suspect that the single quotes and braces in the query is causing the error but don't know how to debug.
#!/usr/bin/perl -w
use strict;
use warnings;
use File::Basename;
use DBI;
use DBD::mySQL;
my $data_path="D:\\NickD\\Project\\StockData\\";
my $db = "TestMMDB";
my $user = "user";
my $pass ="pass";
my $host = "localhost";
my $query ="";
my #row;
my #files = glob("$data_path*.csv");
DBI->trace(1);
my $dbh = DBI->connect("dbi:mysql:$db:$host",$user,$pass);
foreach my $file(#files){
my $filename = basename($file);
my ($db_table,$date) = split("_",$filename);
$query = q{LOAD DATA INFILE ? INTO TABLE ? FIELDS TERMINATED BY ',' (Date,Symbol,Open,High,Low,Close,Volume)};
my $sqlQuery = $dbh->prepare($query);
my $rv = $sqlQuery->execute($file,$db.".".$db_table) or die "Oops!: Can't execute the query :".$sqlQuery->errstr;
while (#row = $sqlQuery->fetchrow_array()) {
print "#row\n";
}
}
my $rc = $dbh->disconnect();
exit(0);
All help will be greatly appreciated.

Update MySQL within Perl loop failing (fetchrow_array)

I've created a Perl script which is meant to loop through an array (a shortlist of customers who meet certain criteria), execute an external command using system() , then update a field within each row once the operation has completed.
It works on the first record (ie external command executes, customer record updates), however when it gets to the second record I receive this error:
DBD::mysql::st fetchrow_array failed: fetch() without execute() at customer_update.pl
Through some googling I added the $sth->finish(); command, however whether I include it or not (either inside the loop as shown, or straight afterward) I still get the same error.
Can anyone shed any light for me as to what I am doing wrong here?
Here's an extract:
# PERL MYSQL CONNECT()
$dbh = DBI->connect('dbi:mysql:signups', $user, $pw)
or die "Connection Error: $DBI::errstr\n";
# DEFINE A MySQL QUERY
$myquery = "SELECT * FROM accounts WHERE field3 = false";
$sth = $dbh->prepare($myquery);
# EXECUTE THE QUERY
$sth->execute
or die "SQL Error: $DBI::errstr\n";
#records = $sth->rows;
print "Amount of new customers: #records\n\n";
while ( my ($field1, $field2, $field3) = $sth->fetchrow_array() ) {
#execute external command via system();
$update_customer_status = "UPDATE accounts SET field3=true WHERE id=$id";
$sth = $dbh->prepare($update_customer_status);
$sth->execute
or die "SQL Error: $DBI::errstr\n";
print "Customer record modified & MySQL updated accordingly\n\n";
$sth->finish();
}
Building a SQL statement with variables and then prepare()ing it defeats the purpose of the prepare. You should build the SQL statement with a placeholder ? instead of $id, prepare() it, and then execute($id) it. As it is, you are leaving yourself open to SQL injection attacks.
Also, it seems that you are not using the warnings and strict pragmas. These two lines should be at the top of every program you write:
use warnings;
use strict;
They will save you much heartache and frustration in the future.
In your loop, you overwrite the handle over from which you are fetching. Use a different variable. (Changing $sth = ...; to my $sth = ...; will do.) While we're at it, let's move the prepare out of the loop.
my $sth_get = $dbh->prepare("SELECT * FROM accounts WHERE field3 = false");
my $sth_upd = $dbh->prepare("UPDATE accounts SET field3=true WHERE id = ?");
$sth_get->execute();
while ( my ($field1, $field2, $field3) = $sth_get->fetchrow_array() ) {
...
$sth_upd->execute($id);
}
You are stomping on your $sth variable when you execute this line ...
$sth = $dbh->prepare($update_customer_status);
Why not save off the result of $sth->fetchrow_array() to an array variable.
Something like ...
my #select_results_AoA = $sth->fetchrow_array();
... and then iterate over the array ...
for my #row ( #select_resilts_AoA ) {
... instead of ...
while ( my ($field1, $field2, $field3) = $sth->fetchrow_array() ) {

printing contents when connected to database using perl

Below, is the code to connect mysql database and retrieving results using perl.
In the below example, samples table has 10 columns. I just want the second and third columns of record 99 into variables.
Can some one help me in this?
use strict;
use warnings;
use DBI;
my $dbh = DBI->connect('dbi:mysql:perltest','root','password') or die "Connection Error: $DBI::errstr\n";
my $sql = "select * from samples where record='99'";
my $sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (my #row = $sth->fetchrow_array) {
print "#row\n";
}
Thanks in advance
This code will get you the second and third columns of the row into variables:
while (my #row = $sth->fetchrow_array) {
$var1 = #row[1];
$var2 = #row[2];
}

How do I call MySQL stored procedures from Perl?

How do I call MySQL stored procedures from Perl? Stored procedure functionality is fairly new to MySQL and the MySQL modules for Perl don't seem to have caught up yet.
MySQL stored procedures that produce datasets need you to use Perl DBD::mysql 4.001 or later. (http://www.perlmonks.org/?node_id=609098)
Below is a test program that will work in the newer version:
mysql> delimiter //
mysql> create procedure Foo(x int)
-> begin
-> select x*2;
-> end
-> //
perl -e 'use DBI; DBI->connect("dbi:mysql:database=bonk", "root", "")->prepare("call Foo(?)")->execute(21)'
But if you have too old a version of DBD::mysql, you get results like this:
DBD::mysql::st execute failed: PROCEDURE bonk.Foo can't return a result set in the given context at -e line 1.
You can install the newest DBD using CPAN.
There's an example in the section on Multiple result sets in the DBD::mysql docs.
#!/usr/bin/perl
# Stored Proc - Multiple Values In, Multiple Out
use strict;
use Data::Dumper;
use DBI;
my $dbh = DBI->connect('DBI:mysql:RTPC;host=db.server.com',
'user','password',{ RaiseError => 1 }) || die "$!\n";
my $sth = $dbh->prepare('CALL storedProcedure(?,?,?,?,#a,#b);');
$sth->bind_param(1, 2);
$sth->bind_param(2, 1003);
$sth->bind_param(3, 5000);
$sth->bind_param(4, 100);
$sth->execute();
my $response = $sth->fetchrow_hashref();
print Dumper $response . "\n";
It took me a while to figure it out, but I was able to get what I needed with the above. if you need to get multiple return "lines" I'm guessing you just...
while(my $response = $sth->fetchrow_hashref()) {
print Dumper $response . "\n";
}
I hope it helps.
First of all you should be probably connect through the DBI library and then you should use bind variables. E.g. something like:
#!/usr/bin/perl
#
use strict;
use DBI qw(:sql_types);
my $dbh = DBI->connect(
$ConnStr,
$User,
$Password,
{RaiseError => 1, AutoCommit => 0}
) || die "Database connection not made: $DBI::errstr";
my $sql = qq {CALL someProcedure(1);} }
my $sth = $dbh->prepare($sql);
eval {
$sth->bind_param(1, $argument, SQL_VARCHAR);
};
if ($#) {
warn "Database error: $DBI::errstr\n";
$dbh->rollback(); #just die if rollback is failing
}
$dbh->commit();
Mind you i haven't tested this, you'll have to lookup the exact syntax on CPAN.
Hi, similar to above but using SQL exec. I could not get the CALL command to work. You will need to fill in anything that is within square brackets and remove the square brackets.
use DBI;
#START: SET UP DATABASE AND CONNECT
my $host = '*[server]*\\*[database]*';
my $database = '*[table]*';
my $user = '*[user]*';
my $auth = '*[password]*';
my $dsn = "dbi:ODBC:Driver={SQL Server};Server=$host;Database=$database";
my $dbh = DBI->connect($dsn, $user, $auth, { RaiseError => 1 });
#END : SET UP DATABASE AND CONNECT
$sql = "exec *[stored procedure name]* *[param1]*,*[param2]*,*[param3]*;";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";