sql - 如何仅在发现重复或以其他方式插入数据时更新记录?

标签 sql mysql perl dbi

在下面的代码中有一个散列,其中包含具有类似 name 字段的记录, pid , typetime1 . pidname是包含重复项的重复字段。

我重复发现更新需要修改的字段 否则在此处插入 namepid有重复项(重复字段)。

其余的都是独一无二的。我在创建表时也有一个独特的字段 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/

相关文章:

sql - 为具有复杂关系的 3 个表创建 View

使用通配符变量连接 SQL 表

linux - 在 IO-Socket-IP/t/04local_client_v6.t 上安装 perl 5.20.3 失败

php - SQL注入(inject)——还有什么?

javascript - 根据值设置表单名称

php - 显示 PHP Mysql 数组的内容

php - 我从我的表单提交中获得了一些双数据库条目

multithreading - 如何使用 Log4perl 在多线程 Perl 应用程序中轮换日志文件

javascript - Selenium:无法在 GWT 应用程序中找到元素

sql - 来自数据库的困难分组报告