且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在java中将生成的pdf文件保存到mysql数据库中

更新时间:2023-01-30 19:02:15


  1. 您可以使用的数据类型是BLOB

  2. 转换PDF文件并在DB中保存byte []数组。

  1. Datatype that you can use is BLOB
  2. Convert the PDF file and persist the byte[] array in DB.

private byte[] getByteArrayFromFile(final Document handledDocument) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final InputStream in = new FileInputStream(handledDocument);
final byte[] buffer = new byte[500];
int read = -1;
while ((read = in.read(buffer)) > 0) {
    baos.write(buffer, 0, read);
}
in.close();
return baos.toByteArray();
}


  • 将其插入数据库如果您使用的是任何ORM工具只需要将列映射为blob,工具将为您处理它。如果您没有使用它,那么您可以创建一个准备好的声明。 Statement有一个名为setBlob()的方法,它将非常有用。考虑下面的示例并使用blob列创建一个普通的插入查询。

  • To insert it into DB If you are using any ORM tools you just have to map the column as blob and the tool will handle it for you. In case you are not using it then you can create a prepared statement. Statement has a method called setBlob() which will be useful. Consider the below example and create a normal insert query with blob column.

    String sql = "INSERT INTO testtable(stringcolumn, blobcolumn) VALUES(?,?)";
    PreparedStatement statement = conn.getConnection().prepareStatement(sql);
    statement.setLong(1, version);
    ByteArrayInputStream bais = new ByteArrayInputStream(getByteArrayFromFile(document));
    statement.setBlob(2, bais);          
    statement.execute();
    conn.commit();