如何在 Java 中操作 BLOB?

发布于 2024-12-10 07:13:17 字数 59 浏览 0 评论 0 原文

我有一个返回 BLOB 的数据库过程。谁能告诉我如何操作 BLOB?有没有具体的API可以实现这个功能?

I have a DB procedure which returns a BLOB. Can anyone tell me how to manipulate the BLOB? Is there any specific API for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

北斗星光 2024-12-17 07:13:17

有专门的 API 吗?

当然,是 JDBC API。


您掌握了 Blob 实例就像您从结果集中获取任何值一样。然后,您应该在此 Blob 上使用 get...- 和 set... 方法。

在这里,您基本上有两个选择:

另一种方法是首先跳过与 Blob 的混乱,而是直接通过 ResultSet 接口使用第二种方法(使用流) 。

Is there any specific API for this ?

Sure, the JDBC API.


You get hold of the Blob instance just as you get hold of any value from a result set. You should then use the get...- and set... methods on this Blob.

Here you basically have two options:

An alternative approach is to skip messing with Blob in the first place, and instead use the second approach (with streams) directly through the ResultSet-interface.

花海 2024-12-17 07:13:17

这取决于包含哪种类型的 blob(图像、视频)及其扩展名。我编写了一个简单的程序来从数据库检索图像并将其显示在 JSP 页面中。希望有帮助。

JSP页面

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>                            
    <image src="blobAction"/> 
</body>

Servlet页面

byte[] imgData = blobDao.getInstance().getPhoto();
        response.setContentType("image/gif");
        OutputStream o = response.getOutputStream();
        o.write(imgData);
        o.flush();
        o.close();

调用过程

public byte[] getPhoto() {

    byte[] imgData = null;
    Blob img = null;
    ResultSet rs = null;
    Statement stmt = null;

    try {

        conn = getConnection();
        String sqlQ = "SELECT CONTENT_FILE FROM CONTENT where id = 'something';
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sqlQ);

        while (rs.next()) {
            img = rs.getBlob("CONTENT_FILE");
            imgData = img.getBytes(1, (int) img.length());
        }
        rs.close();
        stmt.close();
        conn.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {           
        return imgData;
    }
}

It depends on which kind of blob contains (image, video) and it's extension. I wrote a simple program to retrieve an image from DB and show it in JSP page. Hope it helps.

JSP Page

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>                            
    <image src="blobAction"/> 
</body>

Servlet Page

byte[] imgData = blobDao.getInstance().getPhoto();
        response.setContentType("image/gif");
        OutputStream o = response.getOutputStream();
        o.write(imgData);
        o.flush();
        o.close();

Calling Procedure

public byte[] getPhoto() {

    byte[] imgData = null;
    Blob img = null;
    ResultSet rs = null;
    Statement stmt = null;

    try {

        conn = getConnection();
        String sqlQ = "SELECT CONTENT_FILE FROM CONTENT where id = 'something';
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sqlQ);

        while (rs.next()) {
            img = rs.getBlob("CONTENT_FILE");
            imgData = img.getBytes(1, (int) img.length());
        }
        rs.close();
        stmt.close();
        conn.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {           
        return imgData;
    }
}
绅刃 2024-12-17 07:13:17

使用简单的 Java JDBC Api,您可以获得 java.sql.Blob结果集

  1. ResultSet.getBlob(index)
  2. ResultSet.getBlob(String columnName)

两者都返回一个 Blob

获得 Blob 后,您可以从 Blob.getBytes() 方法或使用 setBytes() 方法。

更新:看到某些数据库驱动程序供应商不支持 Blob,您可以使用 ResultSet.getBinaryStream()

With Simple Java JDBC Api, you can get a java.sql.Blob back from a ResultSet.

  1. ResultSet.getBlob(index) or
  2. ResultSet.getBlob(String columnName).

Both returns a Blob.

Once you get a Blob, you can get the byte[] back from the Blob.getBytes() method or set using setBytes() method.

Update: Seeing that some Database driver vendors don't support Blob, you can use ResultSet.getBinaryStream().

烟若柳尘 2024-12-17 07:13:17

您可以使用 javax.sql.rowset .serial.SerialBlob

我在我的 SpringBoot & 中使用它Angular4 应用程序如下所示:

  • 从 Angular4 应用程序获取 Base64String
  • 将 Base64String 解码为 byte[]
  • 创建 SerialBlob,如下所示: SerialBlob serialBlob = new SerialBlob(byte[])
  • 使用 JpaRepository 将其存储在数据库中

You can use javax.sql.rowset.serial.SerialBlob.

I'm using it in my SpringBoot & Angular4 application like this:

  • get Base64String from Angular4 app
  • decode Base64String to byte[]
  • create SerialBlob like this: SerialBlob serialBlob = new SerialBlob(byte[])
  • store it in the database with JpaRepository
夜清冷一曲。 2024-12-17 07:13:17

例子

public void Insert(Object obj){
        try {
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(byteArray);
            oos.writeObject(obj);
            PreparedStatement ps= conn1.prepareStatement("insert into vehiculos values(?)");    
            ps.setBytes(1, byteArray.toByteArray());  
            ps.execute();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("ERROR:al hacer un Insert");   
            ex.printStackTrace();
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void ShowData(){
        try {
            Statement stmt = conn1.createStatement();
            String query = "SELECT * FROM vehiculos";
            ResultSet rs = stmt.executeQuery(query);
            Object obj;
            while(rs.next()){
                //Coche c = (Coche)rs.getBlob("coches");
                Blob blob = rs.getBlob("coches");
                ObjectInputStream ois = new ObjectInputStream(blob.getBinaryStream());
                obj = ois.readObject();
                System.out.println(obj.toString());
                System.out.println("");
                /*Blob blob = rs.getBlob("coches");
                byte[] data = blob.getBytes(1, (int)blob.length());*/
                
            }
            rs.close();
            stmt.close();
        
      } catch (SQLException ex) {
            System.out.println("ERROR:al consultar");
            ex.printStackTrace();
      } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void cerrar_Conexion (){
       
        try {  
        conn1.close();
      } catch (SQLException ex) {
            System.out.println("ERROR:al cerrar la conexión");
            ex.printStackTrace();
      }
    }

Example

public void Insert(Object obj){
        try {
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(byteArray);
            oos.writeObject(obj);
            PreparedStatement ps= conn1.prepareStatement("insert into vehiculos values(?)");    
            ps.setBytes(1, byteArray.toByteArray());  
            ps.execute();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("ERROR:al hacer un Insert");   
            ex.printStackTrace();
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void ShowData(){
        try {
            Statement stmt = conn1.createStatement();
            String query = "SELECT * FROM vehiculos";
            ResultSet rs = stmt.executeQuery(query);
            Object obj;
            while(rs.next()){
                //Coche c = (Coche)rs.getBlob("coches");
                Blob blob = rs.getBlob("coches");
                ObjectInputStream ois = new ObjectInputStream(blob.getBinaryStream());
                obj = ois.readObject();
                System.out.println(obj.toString());
                System.out.println("");
                /*Blob blob = rs.getBlob("coches");
                byte[] data = blob.getBytes(1, (int)blob.length());*/
                
            }
            rs.close();
            stmt.close();
        
      } catch (SQLException ex) {
            System.out.println("ERROR:al consultar");
            ex.printStackTrace();
      } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void cerrar_Conexion (){
       
        try {  
        conn1.close();
      } catch (SQLException ex) {
            System.out.println("ERROR:al cerrar la conexión");
            ex.printStackTrace();
      }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文