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
另外還找到一個頁面,提供瞭解決方法