BLOB vs. VARCHAR for storing arrays in a MySQL table

前端 未结 4 2179
终归单人心
终归单人心 2020-12-09 10:38

I\'ve got a design decision to make and am looking for some best practice advice. I have a java program which needs to store a large number (few hundred a day) of floating

4条回答
  •  失恋的感觉
    2020-12-09 10:50

    Store as a BLOB like so (see code example below). I think this is probably better than using java serialization since java's builtin serialization will need 2427 bytes, and non-java applications will have a harder time dealing with the data. That is, should there ever be any non-java applications querying the database in the future.... if not then the builtin serialization is a few less lines.

    public static void storeInDB() throws IOException, SQLException {
    
        double[] dubs = new double[300];
    
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);
        for (double d : dubs) {
            dout.writeDouble(d);
        }
        dout.close();
        byte[] asBytes = bout.toByteArray();
    
        PreparedStatement stmt = null;  // however we normally get this...
        stmt.setBytes(1, asBytes);
    
    }
    
    public static double[] readFromDB() throws IOException, SQLException {
    
        ResultSet rs = null;  // however we normally get this...
        while (rs.next()) {
            double[] dubs = new double[300];
            byte[] asBytes = rs.getBytes("myDoubles");
            ByteArrayInputStream bin = new ByteArrayInputStream(asBytes);
            DataInputStream din = new DataInputStream(bin);
            for (int i = 0; i < dubs.length; i++) {
                dubs[i] = din.readDouble();
            }
            return dubs;
        }
    
    }
    

    Edit: I'd hoped to use BINARY(2400), but MySQL says:

    mysql> create table t (a binary(2400)) ;
    ERROR 1074 (42000): Column length too big for column 'a' (max = 255);
    use BLOB or TEXT instead
    

提交回复
热议问题