数据库
首页 > 数据库> > mysql – 为什么DBI会将整数隐式更改为字符串?

mysql – 为什么DBI会将整数隐式更改为字符串?

作者:互联网

我有一个具有以下结构的MySQL表.

alid       bigint(20),
ndip       varchar(20),
ndregion   varchar(20),
occ_num    int(3),
Delta_Flag int(1)

从表中选择数据后,我将获取所有引用的数据并作为字符串值.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;
use FindBin;
use lib $FindBin::Bin;
use Database;

my $pwd = $FindBin::Bin;

my $db  = Database->new( 'mysql', "$pwd/config.ini" );
my $db1 = Database->new( 'mysql', "$pwd/config2.ini" );

my @tables = qw( AutoTT_AlarmStatus_Major1 );

for my $table ( @tables ) {

    my $query_select = "SELECT alid, ndip, ndregion, occ_num, Delta_Flag FROM $table LIMIT 1";
    my $result = $db->db_get_results( $query_select );

    print Dumper( $result );

    for my $item ( @{$result} ) {

        # Here I want to prepare, bind and insert this data
        # into other table with same structure
    }
}

Database.pm

sub db_get_results {
    my $self = shift;
    my $qry  = shift;

    my $sth  = $self->{dbh}->prepare( $qry );
    $sth->execute();

    my @return = ();
    while ( my @line = $sth->fetchrow_array ) {
        push @return, \@line;
    }

    return \@return;
}

输出:

$VAR1 = [
          [
            '1788353',
            '10.34.38.12',
            'North Central',
            '1',
            '1'
          ]
        ];

为什么DBI隐式将所有整数转换为字符串?

解决方法:

正如@choroba在他的回答中指出的那样,不是DBI正在对数据做任何事情.它只是通过驱动程序模块(在您的情况下为DBD :: mysql)返回.

在DBI文档的General Interface Rules & Caveats部分中,它说:

Most data is returned to the Perl script as strings. (Null values are returned as undef.) This allows arbitrary precision numeric data to be handled without loss of accuracy. Beware that Perl may not preserve the same accuracy when the string is used as a number.

我之前写的那篇文章是在配置perl以支持64位整数的过程中,并且长双浮点类型是不常见的.这些天我建议驱动程序返回最“自然”Perl类型的值,不会有数据丢失的风险.

对于某些可能难以实现的驱动程序,尤其是那些支持从单个句柄返回多个结果集的数据,如DBD :: mysql那样.

我浏览了DBD::mysql docs,但没有看到任何关于这个主题的提及,所以我看了the relevant code,在那里我可以看到当前的DBD :: mysql将数字作为数字返回.还有很多references to recent changes in this area in the Change log.

也许你正在使用旧版本的DBD :: mysql并且应该升级.

标签:dbi,mysql,perl
来源: https://codeday.me/bug/20190727/1553392.html