【问题标题】:How to create unique identifier from a BLOB data type SQLite JDBC如何从 BLOB 数据类型 SQLite JDBC 创建唯一标识符
【发布时间】:2018-10-14 22:38:19
【问题描述】:

我正在通过 JDBC 从 SQLite 表中读取一些数据。表格包含以下列:

[Id:Integer], [parentId:Integer], [Name:String], [Type:Integer], [Data:BLOB]

现在我需要从 BLOB 数据创建一些唯一标识符,因此相同的 BLOB 每次都会生成相同的标识符。截至目前,我正在从 blob 创建一个字节数组,然后对其进行toString能保证唯一性吗?它的 CPU 周期效率高吗? 因为我有很多这样的记录要处理。请建议。以下是我的代码。

public static void scanData(String dbName) {
    String url = "jdbc:sqlite:C:/dbfolder/" + dbName;
    try (Connection con = DriverManager.getConnection(url);
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select * from someTable");) {

        while (rs.next()) {
            Integer type = rs.getInt("Type");
            if (type != null && type.equals(3)) {
                Integer rowId = rs.getInt("Id");
                Integer parentId = rs.getInt("ParentID");
                String name = rs.getString("Name");
                System.out.println("rowId = " + rowId);
                System.out.println("parentId = " + parentId);
                System.out.println("name = " + name);
                System.out.println("type = " + type);

                InputStream is = rs.getBinaryStream("Data");
                if (is != null) {
                    byte[] arr = IOUtils.toByteArray(is);
                    if (arr != null) {
                        System.out.println("Data = " + arr.toString());
                    }
                }
                System.out.println("---------------------------");
            }

        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    } catch (IOException ioe) {
        System.out.println(ioe.getMessage());
    }
}

** IOUtils is used of : org.apache.commons.io.IOUtils

【问题讨论】:

  • 如果你需要一个唯一的字符串,你需要看看散列和加盐。你所拥有的可能会使冲突成为可能,但我并不努力,因为看起来你需要使用散列。 Sqlite 甚至可能内置了它。
  • 下面的评论提到了 GUID,在这种情况下可能更合适。见stackoverflow.com/questions/2982748/create-a-guid-in-java

标签: java sqlite jdbc


【解决方案1】:

要生成唯一标识符,您可以使用 org.apache.commons.codec.digest.DigestUtils 生成 sha256,这样它对于每个 blob 类型都是唯一的

DigestUtils.sha256Hex(new FileInputStream(file));

将 Blob 转换为 inputStream

blob.getBinaryStream();

【讨论】:

  • 请注意,SHA-256 是一种散列算法,根据定义,它可以为不同的 BLOB 输出相同的值(散列冲突)。这种情况发生的可能性取决于数据量(也可能是数据类型)。如果您想要保证唯一值,则需要一个 GUID。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
相关资源
最近更新 更多