#!/usr/bin/perl use warnings; use strict; use DBI; my $dbh; #A lexical scope so that the db... variables go out of scope quickly. { my $dbname = "database"; my $dbuser = "user"; my $dbpass = "password"; my $dbhost = "localhost"; my $dbport = 3306; my $dsn = "DBI:mysql:database=$dbname;host=$dbhost;port=$dbport"; $dbh = DBI->connect($dsn, $dbuser, $dbpass, { RaiseError => 1 }) or die "Couldn't connect to the database: $!\n"; } #Use placeholders here. Your DBD driver will then take care of #appropriate quoting. my $sth = $dbh->prepare("SELECT ID, Data FROM table_name WHERE Data=?"); $sth->execute("value"); #You're executing the update query lots of times. #Prepare it once, then execute it with different values. my $update_sth = $dbh->prepare("UPDATE new_table SET newData=? WHERE newID=?"); #No point doing the looping over your DataHash twice, you've got the data #once, why not use it here? while(my ($id, $data) = $sth->fetchrow) { $update_sth->execute($data, $id); } #I never bother with these if it's at the end of a script personally. #They'll happen automatically when the variables get DESTROY'ed $sth->finish; $update_sth->finish; $dbh->disconnect;