简体   繁体   English

Perl - 在没有主键的情况下更新 mysql 表

[英]Perl - update mysql table without primary key

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:在 Workbench 中,它会引发Error 1175直到我在更新之前执行此行:

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.但是当我尝试在 perl 中执行此操作时,它不起作用。 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?我怎样才能在 perl 中完成这项工作?

UPD.更新。 I updated the code with @@sql_safe_updates check and commit.我用@@sql_safe_updates 检查和提交更新了代码。

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. 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令人困惑的想法是,成功select $rv 为 1,成功update 2

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.关于返回码检查,对于非SELECT语句, execute返回受影响的行数(如果已知)。 . . Zero rows affected (as opposed to an error) is represented as the special "zero but true" value "0E0".受影响的零行(与错误相反)表示为特殊的“零但为真”值“0E0”。 In the OP's case, the statement was returning 2.在 OP 的情况下,该语句返回 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM