Hello i am trying to insert some data into mysql using perl.
i have an array that i want insert into a table. but problem is that the array has a " ' "
.when i try to insert it got an error mysql query failed.
#!/usr/bin/perl
use DBI;
#abc = "FUJI-XEROX CO. LTD. ADVANCED TECH & ENG'G CENTER 9-50 CHUO 2-CHOME, EBINA-SHI KANAGAWA 24 JAPAN";
$dbh = DBI->connect('dbi:mysql:remotegenius;host=localhost', 'root', 'active123') or die "Connection Error: $DBI::errstr\n";
$dbh->do("insert into OUI set `oui`='$abc'");
when i execute code i got
DBD::mysql::db do 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 'G CENTER 9-50 CHUO 2-CHOME, EBINA-SHI KANAGAWA 24 JAPAN'' at line 1 at ./test.pl line 9.
I need someone help from mysql and perl expertise.
First of all it is essential to use strict and use warnings at the top of every program. It saves a huge amount of time by revealing simple mistakes, and would have alerted you to the fact that you put a string into array #abc and then use the scalar $abc in your SQL statement. I assume here that you intended to use $abc throughout.
Your error is because that's not what an INSERT statement looks like. You also need to escape and quote the string in $abc properly as it contains single quotes, so you must write
$dbh->do(sprintf 'INSERT INTO oui (oui) VALUES (%s)', $dbh->quote($abc))
But it is best to prepare the statement first and then execute it
my $insert = $dbh->prepare('INSERT INTO oui (oui) VALUES (?)');
and later
$insert->execute($abc);
Or perhaps you mean "UPDATE oui SET oui = ?"? But that will set the oui field to the same value on every row of the table.
If you need to insert array of values, first make sure you have values in array variable.
#vals = ('One', 'Two', 'Three');
Error is because INSERT query syntax is wrong, here is the INSERT syntax
INSERT INTO <table> (col1, col2) VALUES ('val1', 'val2)
Here is the snippet that should work for you
use DBI;
my #vals = ('One', 'Two', 'Three');
$dbh = DBI->connect('dbi:mysql:remotegenius;host=localhost', 'root', 'active123') or die "Connection Error: $DBI::errstr\n";
my $in = $dbh->prepare('INSERT INTO oui (oui) VALUES (?)');
foreach (#vals) {
$in->execute($_);
}
`
Related
I have already connected MySQL to the database but the problem is that
I have some problems with inserting Data from Perl to Mysql.
The error that pops out is:
Use of uninitialized value in concatenation (.) or string at ./etl_server_info.pl line 204, (Which is the connection of the database )
DBD::mysql::st execute failed: called with 1 bind variables when 0 are needed at ($stmt->execute($sql);)
sub insert_record(){
my($data,$db_config)=#_;
my $result = -1; # -1 fail; 0 - succ
# connect to db
# connect to MySQL database
my $dsn = "DBI:mysql:database=".$db_config->{'Top_Data'}.";host=".$db_config->{'127.0.0.1'}.";port=".$db_config->{'3306'};
my $username = $db_config->{'username'};
my $password = $db_config->{'password'};
my %attr = (PrintError=>0,RaiseError=>1 );
my $dbh = DBI->connect($dsn,$username,$password,\%attr) or die $DBI::errstr;
print "We Have Successfully Connected To The Database \n";
# prepare sql statement
# execute insert
my $sql = 'insert into Top(Load_Average, CPU_us, CPU_id, CPU-wa, CPU_hi, CPU_si, CPU_st, Swap_Total, Swap_Free, Swap_Used, Memory_Total, Memeory_Free, Memory_Used, Memory_Buff, Date) values(float,float,float,float,float,float,float,float,varchar,varchar,varchar,varchar,varchar,varchar,date)';
my $stmt =$dbh->prepare($sql) or die "Its A Fail" . $dbh->errstr();
$stmt->execute($sql);
$stmt->finish();
$dbh->disconnect();
$result = 0;
return($result);
Your use of the $db_config variable looks suspicious to me. Either your config hash is strange, or you're using values instead of keys.
You haven't shown us where $db_config is set up, but I'd guess it looks something like this:
$db_config = {
name => 'Top_Data',
host => '127.0.0.1',
port => 3306,
username => 'someone',
password => 'a secret',
};
And then you would use it like this:
my $dsn = "DBI:mysql:database=".$db_config->{name}.";host=".$db_config->{host}.";port=".$db_config->{port};
Notice that I've used the key names (name, host and port) instead of the values (Top_Data, 127.0.0.1 and 3306).
I'll also point out that you can simplify this slightly by using Perl's ability to expand variables inside a double-quoted string.
my $dsn = "DBI:mysql:database=$db_config->{name};host=$db_config->{host};port=$db_config->{port}";
There's another problem later on, with your SQL statement.
my $sql = 'insert into Top(Load_Average, CPU_us, CPU_id, CPU-wa, CPU_hi,
CPU_si, CPU_st, Swap_Total, Swap_Free, Swap_Used, Memory_Total,
Memeory_Free, Memory_Used, Memory_Buff, Date)
values(float,float,float,float,float,float,float,float,
varchar,varchar,varchar,varchar,varchar,varchar,date)';
The values that you should be inserting are the actual data items. So where you have the strings "float", "varchar" or "date", you should actually have data items (a floating-point number, a string or a date).
Finally, having prepared your statement, you don't need to pass it to the execute() method. You should, however, look at using bind points in your SQL and passing your actual data items to the execute() call
this is my text file
StudentId Name Dept address city
1 Chellappa CSE 22 xx-colony 2nd street coimbatore
2 Vijay IT 23 yy colony coimbatore
In this file (22 xx-colony 2nd street) and (23 yy colony) is address to store in database address column
use DBI;
use strict;
my $driver = "mysql";
my $database = "TESTDB";
my $dsn = "DBI:$driver:database=$database";
my $userid = "root";
my $password = "1234";
my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;
my $query = 'INSERT INTO student (StudentId,Name,Dept,address,city) VALUES (?,?,?,?,?)';
my $sth = $dbh->prepare($query) or die "Prepare failed: " . $dbh->errstr();
open my $fh, "<", "text.txt" or die $!;
<$fh>; #skip header
while (<$fh>)
{
chomp;
my #vals = split;
$sth->execute(#vals);
}
close $fh;
this code is doesn't work properly for that text file anyone can help me
DBD::mysql::st execute failed: called with 8 bind variables when 4 are
needed
That error is not generated by the code that you have shown us. Your code contains this:
my $query = 'INSERT INTO student (StudentId,Name,Dept,address,city) VALUES (?,?,?,?,?)';
That SQL query contains five bind points, not four. It's always important to be accurate when reporting these things.
Anyway, the important thing is that the number of bind points is different to the number of values you pass to execute(). And it's pretty simple to see where that problem comes from.
Your first data line is this:
1 Chellappa CSE 22 xx-colony 2nd street coimbatore
And you split that data into the #vals array with this code:
my #vals = split;
With no arguments, split() splits $_ on whitespace (you can read the documentation online).
So, after running that code on that data, you'll end up with eight values in #vals. Those values are:
1, Chellappa, CSE, 22, xx-colony, 2nd, street, coimbatore
So it's clear that your simple split() isn't processing your data in the way that you expect. You'll need to come up with a more sophisticated way to extract your five expected data items from your input record.
Unfortunately, you don't give us any detail on how your input file is structured, so we can't give you any more help on how to fix your problem.
Update: Guessing at what you might want here, the update statement could become something like:
$sth->update(#vals[0 .. 2], join ' ', #vals[3..6], $vals[7]);
But I have no idea how well that will work with other lines of data that might have the whitespace in other places.
Yes it can be done using join(). Since you have all the values separated by space you are getting this problem. If your file is created by you then you can just add comma separated values like (1, Chellappa, CSE, 22 xx-colony 2nd street,coimbatore). This will help you to fetch all the data using split as follows
split(',',).
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() ) {
when I post something into my html form, for example in the first name field, I enter in:
'John', i am getting the following error:
Error in query: .
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 'Smith',Address_Line_1='rtuy657tr',Address_Line_2='',City='leicester',Postcode='L' at line 1
I know it has something to do with the mysql_real_escape_string () function, but how would I use it for inserting into a the DB. I have started the function:
function db_insert_preparation(){
}
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("project1", $con);
This is where it needs to be used:
$sql2 = "INSERT INTO `".$table_name."` (`Group`, `Date_Of_Birth`, `Gender`, `Title`, `First_Name`, `Last_Name`, `Address_Line_1`, `Address_Line_2`, `City`, `Postcode`, `Contact_No`, `Email`, `Additional_Comment`, `Upload_File`) VALUES ('".db_insert_preparation($group)."','".$_POST[dateofbirth]."','".$_POST[gender]."','".$_POST[title]."','".$_POST[firstname]."','".$_POST[lastname]."','".$_POST[address1]."','".$_POST[address2]."','".$_POST[city]."','".$_POST[postcode]."','".$_POST[contactno]."','".$_POST[email]."','".$_POST[note]."','".$filename."' )";
The SQL insert statement is vulnerable to SQL injection. If one of the POST values contains a double quote " or a newline, the statement gets corrupted and syntax errors ensue. Make sure you escape everything user-provided with mysql_real_escape_string().
use mysql_real_escape_string function on mysql_real_escape_string($_POST[firstname']). Infact do it on all your post variables before you pass it to the SQL.
How to insert text into mysql having quotes using perl ?
It seems difficult to insert text containing ' & ".
I'm using Perl DBI module & DB is mysql.
UPDATE:
here is my query
my $s = "INSERT INTO comment(guid,review_id) VALUES ('$guid','$review_id')";
You should read section 'Placeholders and Bind Values' in man DBI
EDIT: added example
my $s = "insert into comment(guid,review_id) values (?, ?)";
$dbh->do( $s, undef, $guid, $review_id) or die $dbh->errstr;
Your old query would have been something like this:
my $s = "insert into comment(guid,review_id) values ('$guid','$review_id')";
$dbh->do($s);
The better way, using placeholders and bind values as per #AlexD's answer, would look like this:
my $sth = $dbh->prepare("insert into comment(guid,review_id) values (?, ?)";);
$sth->execute($guid, $review_id);
To learn about the security risks of your first approach, have a look at SQL injection attacks on Wikipedia.