我怎样才能发现PostgreSQL中的bytea列包含任何数据?

时间:2015-01-02 09:47:55

标签: postgresql pgadmin

我有包含bytea列的IMAGE表。 bytea列的值可以为null。我在这个表中有三行:

  • id:1,name:“some string”,data:null
  • id:2,name:“small.png”,data:包含小图片(460 B)
  • id:3,name:“large.png”,data:包含大图(4.78 KB)

当我在pgAdmin中查看此表中的数据时,我看到: enter image description here

从输出中我不知道哪一行包含bytea列中的二进制数据,哪一行不包含。 当我运行SQL时选择:

select id, name, data from image;

我得到以下结果,我可以说id 2的行包含一些二进制数据,但我无法区分其他行(id为1和3的行)是否有某些数据或为null:

enter image description here

问题

  • 是否有任何SQL select选项可以查看bytea列中是否有任何数据?
  • 是否有任何pgAdmin设置可以查看bytea列数据?

为了澄清,我附上了Java测试代码,用于保存和从IMAGE表中检索数据。 Image small.png的大小为460B,large.png的大小为4.78KB。

private static final String JDBC_POSTGRESQL = "jdbc:postgresql://localhost/testDB?user=username&password=passwd";
private static File[] files = {new File("small.png"), new File("large.png")};

public static void main(String[] args) {
    // stores just the string
    try (Connection con = DriverManager.getConnection(JDBC_POSTGRESQL)) {
        PreparedStatement ps = con.prepareStatement("insert into image (name) values (?)");
        ps.setString(1, "some string");
        ps.executeUpdate();
    } catch (SQLException e1) {
        e1.printStackTrace();
    }

    // store images
    for (File file : files) {
        try (Connection con = DriverManager.getConnection(JDBC_POSTGRESQL)) {
            byte[] bytes = Files.readAllBytes(file.toPath());
            PreparedStatement ps = con.prepareStatement("insert into image (name, data) values (?, ?)");
            FileInputStream fis = new FileInputStream(file);
            ps.setString(1, file.getName());
            ps.setBinaryStream(2, fis, bytes.length);
            ps.executeUpdate();
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }

    // read from image table and create files
    try (Connection con = DriverManager.getConnection(JDBC_POSTGRESQL)) {
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select name, data from image");
        while (rs.next()) {
            File outputFile = new File("output_" + rs.getString("name"));
            FileOutputStream fos = new FileOutputStream(outputFile);
            if (rs.getBytes("data") != null) {
                fos.write(rs.getBytes("data"));
            }
        }
    } catch (SQLException | IOException e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:6)

您可以使用is null运算符检查NULL值和octet_length()以获取bytea列的实际长度:

select id, 
       name, 
       data is null as data_is_null, 
       octet_length(data) as data_length 
from image;

请注意,如果octet_length()为空,NULL也将返回data,因此您可能只需要它(对于零长度字节,它将返回0,因此您可以将null值与空值区分开来)

由于我不使用pgAdmin,我无法告诉你它是否有任何特殊功能来查看二进制数据

相关问题