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

vit*_*tfo 2 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中查看此表中的数据时,我看到: 在此输入图像描述

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

select id, name, data from image;
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

问题

  • 是否有任何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();
    }
}
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 8

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

select id, 
       name, 
       data is null as data_is_null, 
       octet_length(data) as data_length 
from image;
Run Code Online (Sandbox Code Playgroud)

请注意,如果为null,octet_length()也将返回,因此您可能只需要它(对于零长度bytea,它将返回,因此您可以区分值与空值)NULLdata0null

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

  • @ mr.incognito:http://www.sql-workbench.net(它支持显示二进制数据:http://www.sql-workbench.net/BlobDisplay2_png.html) (2认同)