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];
}
Related
I'm getting this compilation error when running my code. Can anyone help what is wrong with this code. ?
Operating system is AIX
Error -
Can't modify constant item in scalar assignment at pet_logical_date.pl line 29, near "1}" Execution of
pet_logical_date.pl aborted due to compilation errors.
Line 29 is - *print $cgi=>table({border=1});
CODE is -
#!/usr/bin/perl -w
#####################################################################################
$\="\n";
$ENV{ORACLE_HOME}='/oravl01/11.2.0.3';
$LD_LIBRARY_PATH='/oravl01/11.2.0.3/lib';
use Shell;
use DBI ;
use CGI ;
my $cgi = new CGI;
print $cgi->header;
print $cgi->start_html(-title=>'Basic CGI');
my $dsn = "DBI:Oracle:$db_inst";
$dbh = DBI->connect( 'dbi:Oracle:ABC',"DEF","IJK") or die "Database connection not made: $DBI::errstr";
my $sql = qq{SELECT logical_date,logical_date_type from logical_date where expiration_date is null };
my $sth = $dbh->prepare( $sql ) || die $dbh->errstr;
$sth->execute() || die $dbh->errstr;
print $cgi->table({border=1});
print "<tr align=center><th>$sth->{NAME}->[0]</th><th>$sth->{NAME}->[1]</th></tr>";
while (#data = $sth->fetchrow_array()) {
$Logical_Date_O = $data[0];
$Logical_Date_B = $data[1];
$Logical_Date_R = $data[2];
print "<tr><td><font color='black'>$Logical_Date_O</font></td>
<td>$Logical_Date_B</td><td>$Logical_Date_R</td></tr>\n";
}
print $cgi->end_table;
print $cgi->end_html;
Line 29 should be like this:
print $cgi->table( { -border=>"1" } );
There is something else that, although is not the cause of the error can produce some unexpected behavior: your SQL query return a two fields recordset;
but inside the while loop you try to read a third field:
$Logical_Date_R = $data[2];
the variable Logical_Date_R is likely going to have a null value.
print $cgi=>table({border=1}); is trying to assign border=1. I think you meant border => 1 (changing the assignment operator, =, to the fat comma, =>).
I have currently working on perl script.
Select Column1,Column2,Column3.. from table.
This query contain some part in $cmd="Select Column1 ";
and other $cmd1=",Column2,Column3 from table"; // This is dynamic part, so split query in two different variable.
After this execute whole query.
How to do this query splitting part.?
use DBI;
use strict;
use warnings;
# Your input !
my $cmd = "Select Column1 ";
my $cmd1 = ",Column2,Column3 from table";
# I am wondering why you have your query like this ...
# but anyway, lets assume there's a reason behind this!
my $dbh =
DBI->connect(
'DBI:mysql:databasename;host=db.example.com', # TODO Change this
'username', # TODO change this
'password', # TODO change this
{ RaiseError => 1 }
) or die "Could not connect to database: $DBI::errstr";
my $sth = $dbh->prepare( $cmd . $cmd1 );
$sth->execute();
my #row;
while ( #row = $sth->fetchrow_array ) {
print "#row\n";
}
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;
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.
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";