Mysql存储Java BitSet(转)

本文介绍了如何在MySQL数据库中存储和检索Java的BitSet。通过将BitSet转换为字节数组再转化为Blob对象进行存储,读取时则反向转换。使用了java.sql包和jdbcConnector,更新操作通过ResultSet的updateBlob()方法完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Storing and Retrieving java Bitset in MySQL database

I had one of those frustrating days where you spend hours and hours searching around for what should be a simple coding solution, to no avail. Finally I was able to patch together enough disparate knowledge to achieve my goal: namely, storing and retrieving a java BitSet on a MySQL database. Below is the solution, which I hope might help any other unfortunate souls looking for this answer.

 

I’m using the java.sql package along with jdbcConnector. Updates are done using the update functions of ResultSet. I will store the BitSets as Blobs (hehe – Blobs!), but in order to do this they have to be converted first to byte arrays, and then the byte arrays must be converted to Blobs. Once you have a Blob it can be stored on the table with resultSet.updateBlob() or some other method. Conversely, to retrieve the BitSet you must first convert the Blob to a byte array and then to a BitSet.

The methods toByteArray and fromByteArray are purloined from here.

BitSet to Blob (For writing to database):

private static Blob bitsetToBlob(BitSet myBitSet) {
    byte[] byteArray = toByteArray(myBitSet);
    Blob blob = con.createBlob(); //con is your database connection created with DriverManager.getConnection();
    blob.setBytes(1, MACCSarr);

    return blob;
}

private static byte[] toByteArray(BitSet bits) {
    byte[] bytes = new byte[bits.length()/8+1];
    for (int i=0; i<bits.length(); i++) {
        if (bits.get(i)) {
            bytes[bytes.length-i/8-1] |= 1<<(i%8);
        }
    }
    return bytes;
}

Now that you have a Blob you can update the table with resultSet.updateBlob() or some other method.
Blob to BitSet (for reading from database):

private static BitSet blobToBitSet(Blob myBlob) {
    byte[] bytes = blob.getBytes(1, (int)blob.length());
    BitSet bitSet = fromByteArray(bytes);

    return bitSet;
}

private static BitSet fromByteArray(byte[] bytes) {
    BitSet bits = new BitSet();
    for (int i=0; i<bytes.length*8; i++) {
        if ((bytes[bytes.length-i/8-1]&(1<<(i%8))) > 0) {
            bits.set(i);
        }
    }
    return bits;
}

Hope that helps. If I can save just one person from the frustration I just went through, then I have done a good thing

 

 

另外还找到一个页面,提供了解决方法

http://forums.sun.com/thread.jspa?threadID=620650

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值