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'm trying to parse a few references from a file and load them into a MySQL table, but I keep on getting this error everytime I run the script
DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' Njuguna, M.I., Yusuf, J. A., Akama, V.,2013,Animal husbandry in the developed w' at line 1 at manuscripts3.pl line 51, <$fh> line 1.
Uncaught exception from user code
See my code below.
I'm at my wits end. What am I doing wrong?
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
use DBI;
my $driver = "mysql";
my $database = "test";
my $user = "root";
my $password = "";
my $dbh = DBI->connect(
"DBI:$driver:$database",
$user,
$password, {
RaiseError => 1,
PrintError => 1,
AutoCommit => 0,
}
) or die $DBI::errstr;
my $file = "/var/www/manuscripts.txt";
open my $fh, "<", $file;
my #manuscripts;
while (my $lines = <$fh>) {
$lines =~ s/\, \(/\t/g;
$lines =~ s/\) \“/\t/g;
$lines =~ s/\” /\t/g;
my ($authors, $year, $title, $journal) = split(/\t/, $lines);
push #manuscripts, {
authors => $authors,
year => $year,
title => $title,
journal => $journal
};
#print "$title\n";
my $sql = "insert into manuscript($authors,$year,$title,$journal) values (?,?,?,?)";
$dbh->commit();
my $stmt = $dbh->prepare($sql);
$stmt->execute($authors, $year, $title, $journal);
# disconnect from the MySQL database
$dbh->disconnect();
}
#print $manuscripts[0][2];
text file:
Kamau, M.A., Njuguna, M.I., Yusuf, J. A., Akama, V., (2013) “Animal husbandry in the developed world” Journal of Hospital Infenction
Kamau, M.A., Njuguna, M.I., Yusuf, J. A., Akama, V., (2013) “Agriculture and global warming” PLOS Medicine Kamau, M.A., Njuguna,
M.I., Yusuf, J. A., Akama, V., (2013) “Rotational farming as a business” The Journal of Infectious Diseases
The problem is here:
my $sql = "insert into manuscript($authors,$year,$title,$journal)
values (?,?,?,?)";
You are putting the contents of the variables as the field names. I assume you mean:
my $sql = "insert into manuscript(authors,year,title,journal)
values (?,?,?,?)";
You have to use $stmt->bind_param(); to bind the parameter and use $stmt->execute() without parameter
my $sql = "insert into manuscript(authors,year,title,journal)
values (?,?,?,?)";
my $stmt = $dbh->prepare($sql);
$stmt->bind_param(1,$authors);
$stmt->bind_param(2,$year);
$stmt->bind_param(3,$title);
$stmt->bind_param(4,$journal);
$stmt->execute();
I am trying to make a little script to extract databases/tables/columns from my database, but in the first step I couldn't move on, I am getting databases in strange list, please look:
#!/usr/bin/perl
use DBI;
$host = "localhost";
$user = "wnyclick_siteusr";
$pw = "Hank0402\$";
$dsn = "dbi:mysql:$database:localhost:3306";
$connect = DBI->connect($dsn, $user, $pw);
$databases = $connect->selectcol_arrayref('show databases');
use Data::Dumper;
print Dumper $databases;
executing this code giving me the following:
$VAR1 = [
'information_schema',
'wnyclick_sitedatawp'
];
How can I put this execution result in a list?
print #VAR1[0];
print #databases[0];
I just modified your code. Try the below code:
#!/usr/bin/perl -w
use DBI;
use DBD::mysql;
my $user = "wnyclick_siteusr";
my $pw = "Hank0402\$";
#Connecting Database
$dbh = DBI->connect( 'dbi:mysql:database=mysql;host=localhost;port=3306', '$user', '$pw' )
or die "Connection Error: $DBI::errstr\n";
$sql = "show databases";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while ( #row = $sth->fetchrow_array ) {
#print $row[1];
print "#row\n";
}
I am making a code that connects to a database 'peoples', gets data from there and what i need to do is with a button to get the id for the person where this button is clicked and delete or update. The problem is i dont know how to make this i perl because in other languages i did it.
my $q= new CGI;
print $q->header;
print $q-> start_html(
-title => "Main",
-style => {-src =>'/media/css/ui-lightness/jquery-ui-1.10.3.custom.css" rel="stylesheet' },
-script => [
{ -src=>'/media/js/jquery-1.9.1.js'},
{ -src=>'/media/js/jquery-ui-1.10.3.custom.js' }
]
);
print $q->start_form;
print $q->table({},
$q->Tr(
$q->th('Name', 'Surname', 'Age')
));
# Connect to the database
## mysql user database name
my $db = "student";
## mysql database user name
my $user = "root";
## mysql database password
my $pass = "";
## user hostname : This should be "localhost" but it can be diffrent too
my $host="127.0.0.1";
## SQL query
my $query = "select Name,Surname,Age from student";
my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
my $sqlQuery = $dbh->prepare($query)
or die "Can't prepare $query: $dbh->errstr\n";
my $rv = $sqlQuery->execute
or die "can't execute the query: $sqlQuery->errstr";
while ( my ($Name, $Surname, $Age) = $sqlQuery->fetchrow_array() ) {
print STDOUT "$Name $Surname $Age";
$q->button( print $q->button(
-id => 'leletebtn',
-name => 'submit_form',
-value => 'Delete',
)
)
}
print $q->end_form;
print $q->end_html;
There are a lot of tutorials out there. You have to use DBI:
http://oreilly.com/catalog/perldbi/chapter/ch04.html
http://www.perl.com/pub/1999/10/DBI.html
my $lastname = 'test';
my $dbh = DBI->connect('DBI:Oracle:people')
or die "Couldn't connect to database: " . DBI->errstr;#connect
my $sth = $dbh->prepare('SELECT id,uid FROM people WHERE lastname = ?')
or die "Couldn't prepare statement: " . $dbh->errstr;#prepare
$sth->execute($lastname); # Execute the query
while ( my $ref = $sth->fetchrow_hashref() ) {
print "$$ref{'id'} \t $$ref{'uid'}\n";
}
Something is wrong with this code.
#!/use/bin/perl
use strict;
use warnings;
use Frontier::Daemon;
use DBI;
sub credentials {
my ($username, $password) = #_;
my $tablename = "users";
my $user = "db_user";
my $pw = "db_pass";
$dbh = DBI->connect('DBI:mysql:database;host=localhost', $user, $pw, {RaiseError => 1});
$sql = "SELECT username, password FROM $tablename";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
if ($sth->rows > 0) {
$login_response = "Login Successful";
} else {
$login_response = "Invalid Credentials";
return {'login' => $login_response};
die();
}
}
$methods = {'login.credentials' => \&credentials,};
Frontier::Daemon->new(LocalPort => 8080, methods => $methods)
or die "Couldn't start HTTP server: $!";
This is another problem with your code - you're not doing anything with the supplied username and password. You need to add a where clause to your SQL statement, so:
my $sql = 'SELECT * FROM users WHERE username = ? AND password = ? ';
my $sth = $dbh->prepare($sql);
$sth->execute($username, $password);
However, given that your example is selecting all records from the 'users' table, I'd have thought that credentials() would at least be returning some rows. However, I'm afraid that I've not used Frontier::Daemon in the past, so I'm not able to help on that front.
I also can't see how this code would work given that you are using strictures. $dbh, $sql, $sth and $login_response haven't been declared. So make sure that you're using 'my' in the right places - as per my example above.
To fix the problems you mentioned with returning the correct string - the logic in your if statement isn't quite right. You are returning the string 'Login Successful' when there's a successful login and the hashref { login => $login_response } when no user could be found.
I think the confusion arose from the layout of the braces. I must stress that you try and indent you code properly, which will make it much more readable to yourself and other developers when debugging and maintaining the code in the future.
The following logic should do the job.
if($sth->rows > 0){
return "Login Successful";
}
return "Invalid Credentials";