在下面的代码中有一个散列,其中包含具有类似 name
字段的记录, pid
, type
和 time1
.
pid
和 name
是包含重复项的重复字段。
我重复发现更新需要修改的字段
否则在此处插入 name
和 pid
有重复项(重复字段)。
其余的都是独一无二的。我在创建表时也有一个独特的字段 Serial no
.我该如何继续?我只在这段代码中做了一个插入。我不知道如何使用 Perl 将检索到的记录存储到数组中。请指导我。
for my $test11 (sort keys %seen) {
my $test1 = $seen{$test11}{'name'};
my $test2 = $seen{$test11}{'pid'};
my $test3 = $seen{$test11}{'type'};
my $test4 = $seen{$test11}{'time1'};
print "$test11\t$test1$test2$test3$test4\n";
$db_handle = &getdb_handle;
$sth = $dbh->prepare("Select username,pid,sno from svn_log1");
$sth->execute() or die "SQL Error: $DBI::errstr\n";
my $ref = $sth->fetchall_arrayref();
print "hai";
print "****$ref";
$sth = $dbh->prepare("INSERT INTO svn_log1 values('$sno','$test11','$test1','$test4','$test2','$test3')");
$sth->execute() or die "SQL Error: $DBI::errstr\n";
}
最佳答案
我认为你想说的是,如果你已经在数据库中有那个名称/pid 组合,你不想尝试插入一些数据,但我不能告诉我,所以我帮不了你。
但是,这里有一些东西可以清理你的代码。首先,选择合理的变量名。其次,始终,始终,始终在 SQL 语句中使用占位符来保护它们:
for my $test11 ( sort keys %seen ) {
my $name = $seen{$test11}{'name'};
my $pid = $seen{$test11}{'pid'};
my $type = $seen{$test11}{'type'};
my $time1 = $seen{$test11}{'time1'};
my $dbh = getdb_handle();
my $sth = $dbh->prepare("Select username,pid,sno from svn_log1");
$sth->execute() or die "SQL Error: $DBI::errstr\n";
my $ref = $sth->fetchall_arrayref();
# XXX why are we fetching this data and throwing it away?
$sth = $dbh->prepare("INSERT INTO svn_log1 values(?,?,?,?,?,?)");
$sth->execute( $sno, $test11, $name, $time1, $pid, $type )
or die "SQL Error: $DBI::errstr\n";
}
假设您不想在存在“$name”和“$pid”的情况下向数据库中插入某些内容(并进行一些清理以避免一遍又一遍地准备相同的 SQL):
my $dbh = getdb_handle();
my $seen_sth = $dbh->prepare( "Select 1 from svn_log1 where username = ? and pid = ?");
# This really needs to be "INSERT INTO svnlog1 (@columns) VALUES (@placeholders)
my $insert_sth = $dbh->prepare("INSERT INTO svn_log1 values(?,?,?,?,?,?)");
for my $test11 ( sort keys %seen ) {
my $name = $seen{$test11}{'name'};
my $pid = $seen{$test11}{'pid'};
my $type = $seen{$test11}{'type'};
my $time1 = $seen{$test11}{'time1'};
$seen_sth->execute($name, $pid) or die "SQL Error: $DBI::errstr\n";
my @seen = $seen_sth->fetchrow_array;
next if $seen[0];
$insert_sth->execute( $sno, $test11, $name, $time1, $pid, $type )
or die "SQL Error: $DBI::errstr\n";
}
这不是我写这篇文章的方式,但它相当清楚。我怀疑这并不是您真正想要的,但我希望它能让您更接近解决方案。
关于sql - 如何仅在发现重复或以其他方式插入数据时更新记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3343461/