oracle 如何将 zip 文件移动到 Java 中的 blob 列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3517260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 21:18:24  来源:igfitidea点击:

How do I move zip file to blob column in Java?

javaoraclezipinputstreamjava-io

提问by Ironosity

I have a Java program that creates a number of xml file and then zips them up and saves them to the file system. Later in the program I want to put that same zip file into a blob column of my oracle database. Problem is I'm not sure how to do that. I don't need to read it or do anything with the data, just move it to the database for persistent, central storage.

我有一个 Java 程序,它创建了许多 xml 文件,然后将它们压缩并保存到文件系统中。稍后在程序中,我想将相同的 zip 文件放入我的 oracle 数据库的 blob 列中。问题是我不知道该怎么做。我不需要读取它或对数据做任何事情,只需将它移动到数据库中以进行持久的中央存储。

Thanks!

谢谢!

回答by ColinD

There are several ways you can do this, but PreparedStatement.setBinaryStreamis probably the best way.

有几种方法可以做到这一点,但PreparedStatement.setBinaryStream可能是最好的方法。

public void saveFileToDatabase(File file) {
  InputStream inputStream = new FileInputStream(file);

  Connection conn = ...;
  PreparedStatement pS = conn.prepareStatement(...);
  ...
  pS.setBinaryStream(index, inputStream, (int) file.length());
  ...
  pS.executeUpdate();
}

(Note that for simplicity I didn't include any of the necessary try/catch stuff for closing the Connection, PreparedStatementand InputStream, but you would need to do that.)

(请注意,为简单起见,我没有包含关闭Connection,PreparedStatement和 的任何必要的 try/catch 内容InputStream,但您需要这样做。)

Done this way, the data will be streamed from the file to the database without having to be loaded in to memory all at once.

通过这种方式,数据将从文件流式传输到数据库,而无需一次性加载到内存中。

回答by Amir Afghani

I think you're looking to use the setBytes()method :

我认为您正在寻找使用该setBytes()方法:

So an example for a table representing e-mails where the body is a stream of bytes would look like:

因此,表示正文为字节流的电子邮件的表的示例如下所示:

      PreparedStatement ps = con.prepareStatement(
        "INSERT INTO Image (ID, Subject, Body) VALUES (2,?,?)");
      ps.setString(1, subject);
      byte[] bodyIn = {(byte)0xC9, (byte)0xCB, (byte)0xBB,
        (byte)0xCC, (byte)0xCE, (byte)0xB9,
        (byte)0xC8, (byte)0xCA, (byte)0xBC,
        (byte)0xCC, (byte)0xCE, (byte)0xB9,
        (byte)0xC9, (byte)0xCB, (byte)0xBB};
      ps.setBytes(2, bodyIn);
      int count = ps.executeUpdate();
      ps.close();

I'm assuming you can easily convert call getBytes()for your Zipped XML object.

我假设您可以轻松转换getBytes()对 Zipped XML 对象的调用。