データベース内のドキュメントをシリアル化して操作する

ドキュメントを操作するときに実行する必要があるタスクの1つは、データベースとの間でDocumentオブジェクトを格納および取得することです。 たとえば、任意のタイプのコンテンツ管理システムを実装している場合は、これが必要になります。 以前のバージョンの文書はすべてデータベースシステムに保存する必要があります。 データベースに文書を格納する機能は、アプリケーションがwebベースのサービスを提供する場合にも非常に便利です。

Aspose.Wordsは、データベース内でこの文書を処理するために、文書をバイト配列に変換する機能を提供します。

文書をバイト配列に変換する

ドキュメントをデータベースに格納したり、web経由で送信するためのドキュメントを準備するには、多くの場合、ドキュメントをシリアル化してバイトアレイを取得する必要があります。

DocumentオブジェクトをAspose.Wordsでシリアル化するには:

  1. DocumentクラスのSaveメソッドオーバーロードを使用してMemoryStreamに保存します。
  2. ToArray メソッドを呼び出します。このメソッドは、ドキュメントをバイト形式で表すバイト配列を返します。

上記の手順を逆にして、バイトをDocumentオブジェクトにロードし直すことができます。

次の例は、Documentオブジェクトをシリアル化してバイト配列を取得する方法と、バイト配列をシリアル化解除してDocumentオブジェクトを再度取得する方法を示:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Load the document.
Document doc = new Document(dataDir + "Test File (doc).doc");
// Create a new memory stream.
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// Save the document to stream.
doc.save(outStream, SaveFormat.DOCX);
// Convert the document to byte form.
byte[] docBytes = outStream.toByteArray();
// The bytes are now ready to be stored/transmitted.
// Now reverse the steps to load the bytes back into a document object.
ByteArrayInputStream inStream = new ByteArrayInputStream(docBytes);
// Load the stream into a new document object.
Document loadDoc = new Document(inStream);

データベース内の文書の保存、読み取り、削除

このセクションでは、文書をデータベースに保存し、それを処理するためにDocumentオブジェクトにロードする方法を示します。 簡単にするために、ファイル名は、データベースから文書を格納および取得するために使用されるキーです。 データベースには2つの列が含まれています。 最初の列"FileName"は文字列として格納され、文書を識別するために使用されます。 2番目の列"FileContent"は、文書オブジェクトをバイト形式で格納するBLOBオブジェクトとして格納されます。

次のコード例は、データベースへの接続を設定し、コマンドを実行する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String url1 = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123";
// Open a database connection.
Connection mConnection = DriverManager.getConnection(url1, user, password);

次のコード例は、ドキュメントをデータベースに保存し、同じドキュメントを再度読み取り、最後にドキュメントを含むレコードをデータベースから削除する方:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Store the document to the database.
StoreToDatabase(doc, mConnection);
// Read the document from the database and store the file to disk.
Document dbDoc = ReadFromDatabase(dataDir + fileName, mConnection);
// Save the retrieved document to disk.
dbDoc.save(dataDir + fileName);
// Delete the document from the database.
DeleteFromDatabase(dataDir + fileName, mConnection);
// Close the connection to the database.
mConnection.close();

文書をデータベースに保存する

データベースに文書を保存するには、この資料の冒頭で説明したように、この文書をバイト配列に変換します。 次に、このバイト配列をデータベースフィールドに保存します。

次のコード例は、指定したデータベースにドキュメントを保存する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void StoreToDatabase(Document doc, Connection mConnection) throws Exception {
// Create an output stream which uses byte array to save data
ByteArrayOutputStream aout = new ByteArrayOutputStream();
// Save the document to byte array
doc.save(aout, SaveFormat.DOCX);
// Get the byte array from output steam
// the byte array now contains the document
byte[] buffer = aout.toByteArray();
// Get the filename from the document.
String fileName = doc.getOriginalFileName();
String filePath = fileName.replace("\\", "\\\\");
// Create the SQL command.
String commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + filePath + "', '" + buffer
+ "')";
Statement statement = mConnection.createStatement();
statement.executeUpdate(commandString);
}

すべての作業を行うSQL式であるcommandStringを指定します:

  • 文書をデータベースに保存するには、“INSERTINTO"コマンドが使用され、FileNameとFileContentの二つのレコードフィールドの値とともにテーブルが指定されます。 追加のパラメータを回避するために、ファイル名はDocumentオブジェクト自体から取得されます。 FileContentフィールド値には、格納されているドキュメントのバイナリ表現を含むメモリストリームからのバイトが割り当てられます。
  • 残りのコード行は、Aspose.Wordsドキュメントをデータベースに格納するコマンドを実行します。

データベースからドキュメントを取得する

データベースからドキュメントを取得するには、ドキュメントデータを含むレコードをバイト配列として選択します。 次に、レコードからバイト配列をMemoryStreamにロードし、MemoryStreamからドキュメントをロードするDocumentオブジェクトを作成します。

次のコード例は、このドキュメントを取得するためのキーとしてファイル名を使用して、指定されたデータベースからドキュメントを取得して返す方法:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static Document ReadFromDatabase(String fileName, Connection mConnection) throws Exception {
// Create the SQL command.
String commandString = "SELECT * FROM Documents WHERE FileName=?";
PreparedStatement statement = mConnection.prepareStatement(commandString);
statement.setString(1, fileName);
Document doc = null;
ResultSet result = statement.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("FileContent");
InputStream inputStream = blob.getBinaryStream();
doc = new Document(inputStream);
inputStream.close();
System.out.println("File saved");
}
result.close();
return doc;
}

データベースから文書を削除する

データベースからドキュメントを削除するには、Documentオブジェクトを操作せずに適切なSQLコマンドを使用します。

次のコード例は、レコードを取得するファイル名を使用して、データベースからドキュメントを削除する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static void DeleteFromDatabase(String fileName, Connection mConnection) throws Exception {
// Create the SQL command.
String commandString = "DELETE FROM Documents WHERE FileName='" + fileName + "'";
Statement statement = mConnection.createStatement();
// Delete the record.
statement.execute(commandString);
}