I have a table with no primary key. I need to execute the following:
UPDATE t1
SET tstamp = now()
WHERE `col1` = 1
AND `col2` = 'this';
In Workbench it throws Error 1175
until I execute this line before the update:
SET SQL_SAFE_UPDATES = 0;
With this line it works just fine.
But when I try to do this in perl it doesn't work. I tried both
$dbh->do("SET SQL_SAFE_UPDATES = 0");
and
my $dbh = DBI->connect("DBI:mysql:$db:$host:$port",$user,$password, { RaiseError => 1, AutoCommit => 0, sql_safe_updates => 0 })
but it still doesn't work.
How can I get this work in perl?
UPD. I updated the code with @@sql_safe_updates check and commit.
The code:
$sth = $dbh->prepare("SELECT @\@sql_safe_updates"); $sth->execute; while(my @row = $sth->fetchrow_array) { print "sql_safe_updates before: ". $row[0] . "\n"; }
$dbh->do("SET SQL_SAFE_UPDATES = 0") or die $dbh->errstr;
$sth = $dbh->prepare("SELECT @\@sql_safe_updates"); $sth->execute; while(my @row = $sth->fetchrow_array) { print "sql_safe_updates after: " . $row[0] . "\n"; }
$query = "UPDATE t1 SET tstamp = now() WHERE `col1` = 1 AND `col2` = 'this'";
$sth = $dbh->prepare($query);
$rv = $sth->execute or die $sth->err();
$dbh->commit;
if ("$rv" ne "1") {
$query =~ s/\n/ /g; $query =~ s/ / /g;
print "Failed to run query: $query\n";
exit;
}
Output:
sql_safe_updates before: 0
sql_safe_updates after: 0
Failed to run query: UPDATE t1 SET tstamp = now() WHERE `col1` = 1 AND `col2` = 'this'
UPD2. I checked the table - everything works after I commited. It is confusing thought, that $rv is 1 on successful select
and 2 on successful update
It was a return code check error, and a missing commit.
Regarding the return code check, for a non- SELECT
statement, execute
returns the number of rows affected, if known. . Zero rows affected (as opposed to an error) is represented as the special "zero but true" value "0E0". In the OP's case, the statement was returning 2.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.