加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl DBI 自动选择更新部分字段的值

发布时间:2020-12-15 23:59:39 所属栏目:大数据 来源:网络整理
导读:通常,有一个表有多个字段,有时候会只修改其中的某些字段,定义为NULL的字段不更新,如下updatefield函数。 #!/usr/bin/perluse strict;use DBI;use constant { NULL = '',null = ''};# 连接到数据库my $dbh = DBI-connect("dbi:SQLite:dbname=gspider.db",

通常,有一个表有多个字段,有时候会只修改其中的某些字段,定义为NULL的字段不更新,如下updatefield函数。

#!/usr/bin/perl
use strict;
use DBI;
use constant {
    NULL => '',null => ''
};

# 连接到数据库
my $dbh = DBI->connect("dbi:SQLite:dbname=gspider.db","",{ RaiseError => 1,AutoCommit => 0 });

# 创建表
#$dbh->do("create table test(id INT primary key,number,name)");                
# 插入数据
#$dbh->do("insert into test values(1,6838472,'a')");
#$dbh->do("insert into test values(2,'e')");
#$dbh->do("insert into test values(3,'f')");


#updatefield(123,'e');
updatefield(NULL,'e');

#查询数据
my $sql = "SELECT * FROM test";
my $dbconn = $dbh->prepare($sql);
$dbconn->execute();

my $table = $dbconn->fetchall_arrayref;
my($i,$j);
for $i ( 0 .. $#{$table} ) {
    for $j ( 0 .. $#{$table->[$i]} ) {
        print "$table->[$i][$j]t";
    }
    print "n";
}

$dbh->commit();
$dbh->disconnect();
<>;

sub updatefield{
    my ($number,$name) = @_;
    my ($field,$fieldword);
    if(undef == $number){
        $field='%s';
        $fieldword='';
    }
    else{
        $field=',number=%s';
        $fieldword=$dbh->quote_identifier($number);
    }
    my $sql = sprintf("update test set name= 's' $field where name=%s ",$fieldword,$dbh->quote($name));
    $dbh->do($sql);
    $dbh->commit();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读