gpt4 book ai didi

sql - 如何更新循环中 SELECT 返回的行?

转载 作者:IT王子 更新时间:2023-10-29 06:27:50 24 4
gpt4 key购买 nike

我在 SQL SELECT 语句返回的行上有一个循环,并且在对行数据进行一些处理之后,有时我想更新行的值。循环体中的处理非常重要,我不能用 SQL 编写它。当我尝试对所选行执行更新时,出现错误(在 Perl 的 DBD::SQLite::st 下执行失败:数据库表被锁定)。是否有一种可读、高效且可移植的方式来实现我正在尝试做的事情?如果做不到这一点,是否有 DBD 或 SQLite 特定的方法来做到这一点?

显然,我可以将更新推送到单独的数据结构中并在循环后执行它们,但我不喜欢代码的处理方式。

如果您有兴趣,这里是相应的 Perl 代码。

my $q = $dbh->prepare(q{
SELECT id, confLoc FROM Confs WHERE confLocId ISNULL});
$q->execute or die;
my $u = $dbh->prepare(q{
UPDATE Confs SET confLocId = ? WHERE id = ?});
while (my $r = $q->fetchrow_hashref) {
next unless ($r->{confLoc} =~ m/something-hairy/);
next unless ($locId = unique_name_state($1, $2));
$u->execute($locId, $r->{id}) or die;
}

最佳答案

暂时启用AutoCommit:

sqlite> .header onsqlite> select * from test;fieldonetwo
#!/usr/bin/perl

use strict;
use warnings;

use DBI;

my $dbh = DBI->connect('dbi:SQLite:test.db', undef, undef,
{ RaiseError => 1, AutoCommit => 0}
);

test_select_with_update($dbh);

sub test_select_with_update {
my ($dbh) = @_;
local $dbh->{AutoCommit} = 1;
my $q = $dbh->prepare(q{SELECT field FROM test});
my $u = $dbh->prepare(q{UPDATE test SET field = ? WHERE field = ?});
$q->execute or die;
while ( my $r = $q->fetchrow_hashref ) {
if ( (my $f = $r->{field}) eq 'one') {
$u->execute('1', $f) or die;
}
}
}

代码运行后:

sqlite> .header onsqlite> select * from test;field1two

关于sql - 如何更新循环中 SELECT 返回的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1305976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com