Java 字符串转数字的大数据处理

       接触java当中对超大数据的处理,因为mysql数据库对应的字段类型是vachar(50),存储的是纯数字的20位长度的唯一标识码,为了方便唯一标识码自增,采取查询数据库最大值后按通道数量(业务自增量)进行自增。这就涉及要将vachar类型强转为数字类型,已知强转的数据类型为UNSIGNED(最大支持18446744073709551615)或DECIMAL,我这里采用DECIMAL,java对应的类型为BigDecimal。

数据库类型转换测试:

SELECT CONVERT('22222222222222222222',SIGNED ) sn0,
       CONVERT('22222222222222222222',UNSIGNED ) sn1,
       CAST('2222222222222222222234' AS DECIMAL(20)) sn2,
       '22222222222222222222'+0 sn3,
       CONVERT('22222222222222222222',DECIMAL(20) ) sn4;

执行结果: 

s0 s1 s2 s3 s4
-1        18446744073709551615    99999999999999999999  2.222222222222222e19 22222222222222222222

 

 

 

数据库查询各表中取最大的channel_sn的值:

SELECT MAX(IFNULL(maxSn.chnSn,0)) sn FROM (

SELECT MAX(CONVERT(a.CHANNEL_SN,DECIMAL(20))) chnSn
FROM ADM_DEV_ENCODER_CHN a

UNION

SELECT MAX(CONVERT(b.CHANNEL_SN,DECIMAL(20))) chnSn
FROM ADM_DEV_SCREENCTRLIN_CHN b

UNION

SELECT MAX(CONVERT(c.CHANNEL_SN,DECIMAL(20))) chnSn
FROM ADM_DEV_DECODER_CHN c

UNION

SELECT MAX(CONVERT(d.CHANNEL_SN,DECIMAL(20))) chnSn
FROM ADM_DEV_VOICE_CHN d

UNION

SELECT MAX(CONVERT(e.CHANNEL_SN,DECIMAL(20))) chnSn
FROM ADM_DEV_LED_CHN e

) maxSn;

 代码测试如下:

public static void main(String[] args) {

        SortedSet chnSnSet = new TreeSet<>();
        SortedSet chnSnSet1 = new TreeSet<>();
        BigDecimal maxChnSn = new BigDecimal("33010800001110000002");
        BigDecimal initChnSn = new BigDecimal("33010800001110000001");
        if (maxChnSn.compareTo(new BigDecimal("0")) > 0) {
            // 根据通道数自动新增序列值
            for (int i = 1; i <= 3; i++) {
                // 依次自增1
                initChnSn = initChnSn.add(new BigDecimal("1"));
                chnSnSet.add(initChnSn.toString());
                chnSnSet1.add(initChnSn);
            }
        } else {
            chnSnSet.add(initChnSn.toString());
            chnSnSet1.add(initChnSn);
        }
        int i=1;
        for (String sn: chnSnSet) {
            System.out.println("chnSnSet_" + i + " = " + sn);
            i++;
        }

        System.out.println("chnSnSet:" + chnSnSet.toString());
        System.out.println("chnSnSet1:" + chnSnSet1.toString());
    }

 

测试输出:

chnSnSet_1 = 33010800001110000002
chnSnSet_2 = 33010800001110000003
chnSnSet_3 = 33010800001110000004
chnSnSet:[33010800001110000002, 33010800001110000003, 33010800001110000004]
chnSnSet1:[33010800001110000002, 33010800001110000003, 33010800001110000004]

 

总结: 

      MYSQL数据库字符串类型转换为数字类型的,注意转换的长度,否则只按该长度的最大值返回结果。Java数据类型中,建议与数据看返回类型匹配,使用BigInteger或BigDecimal。

你可能感兴趣的:(java随笔)