简体   繁体   English

Perl MySQL DBI-更新并获取上一个值

[英]Perl MySQL DBI - update and get last value

I am using the Perl DBI module with MySQL and trying to get the initial value before adding 1 to it when updating a row. 我正在将Perl DBI模块与MySQL配合使用,并尝试在更新行时将其添加1之前获得初始值。

If the current value was 1000 I need to return the value of 1000 and then add 1 to the value. 如果当前值为1000,我需要返回值1000,然后将值加1。

I use this statement in perl to use one transaction... 我在perl中使用此语句来使用一个事务...

update TABLE_NAME set ID = (\@cur_value := ID) + 1

I know I can do a select then an update as two statements or lock the tables manually but transactions happen so fast on our platform that it may cause inconsistencies and this is the fastest way to do it. 我知道我可以选择然后更新为两个语句,也可以手动锁定表,但是事务在我们的平台上发生得如此之快,以至于可能导致不一致,这是最快的方法。

However I simply cannot find a way to return the original value before the increment using this statement. 但是,我根本找不到使用此语句在增量之前返回原始值的方法。

It works fine in ASP as below: 它在ASP中可以正常工作,如下所示:

qry = "update V15_TRACKING set TRACKING_ID = (@cur_value := TRACKING_ID) + 1 where TRACKING_TYPE='ABC'"
Set oRS = oConn.Execute(qry)
qry = "select @cur_value"
if not oRS.EOF then
        while not oRS.EOF
            CurrTrackingID = oRs.Fields("@cur_value")
            oRS.movenext
        wend
    oRS.close
    end if

Please can someone advise me what I need to do to return the original value in Perl as I have searched everywhere and tried all sorts of solutions. 请问有人可以告诉我在Perl中返回原始值需要做些什么,因为我到处搜索并尝试了各种解决方案。

A snippet to show what you're actually doing in perl, and your result would help diagnose what is going on in your script. 显示您在perl中实际执行的操作的代码段,其结果将有助于诊断脚本中正在发生的事情。

I tried this trivial example: 我尝试了这个简单的例子:

The DB: 数据库:

CREATE DATABASE TEST;

CREATE TABLE foo (
    id  int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    val int(11) NOT NULL
);

INSERT INTO foo (val) VALUES (1);

And the Perl 和Perl

#!/bin/env perl
use strict;
use warnings;

use Data::Dumper;
use DBI;

my $dbh = DBI->connect('DBI:mysql:database=test', 'dbuser', 'dbpass');

my $select = $dbh->prepare('SELECT * FROM foo WHERE id=?');
my $select_old_val = $dbh->prepare('SELECT @old_val');
my $update = $dbh->prepare('UPDATE foo SET val=(@old_val := val) + 1 WHERE id=?');

$update->execute(1);
$select_old_val->execute();
$select->execute(1);

while (my $row = $select_old_val->fetchrow_hashref) {
    print Dumper $row;
}


while (my $row = $select->fetchrow_hashref) {
    print Dumper $row;
}

And after a few goes: 几步之后:

$ perl select_and_update.pl 
$VAR1 = {
          '@old_val' => '10'
        };
$VAR1 = {
          'id' => '1',
          'val' => '11'
        };

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

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