Tuần tự hóa và làm việc với một tài liệu trong cơ sở dữ liệu
Một trong những nhiệm vụ bạn có thể cần hoàn thành khi làm việc với tài liệu là lưu trữ và truy xuất các đối tượng Document đến và từ cơ sở dữ liệu. Ví dụ: điều này sẽ cần thiết nếu bạn đang triển khai bất kỳ loại hệ thống quản lý nội dung nào. Tất cả các phiên bản trước của tài liệu phải được lưu trữ trong hệ thống cơ sở dữ liệu. Khả năng lưu trữ tài liệu trong cơ sở dữ liệu cũng cực kỳ hữu ích khi ứng dụng của bạn cung cấp dịch vụ dựa trên web.
Aspose.Words cung cấp khả năng chuyển đổi tài liệu thành mảng byte cho công việc tiếp theo với tài liệu này trong cơ sở dữ liệu.
Chuyển đổi một tài liệu thành mảng byte
Để lưu trữ một tài liệu trong cơ sở dữ liệu hoặc chuẩn bị một tài liệu để truyền qua web, thường cần phải tuần tự hóa tài liệu để thu được một mảng byte.
Để tuần tự hóa một đối tượng Document trong Aspose.Words:
- Lưu nó vào MemoryStream bằng cách sử dụng nạp chồng phương thức Save của lớp Document.
- Gọi phương thức ToArray, phương thức này trả về một mảng byte biểu thị tài liệu ở dạng byte.
Sau đó, các bước trên có thể được đảo ngược để tải các byte trở lại đối tượng Document.
Ví dụ bên dưới cho thấy cách tuần tự hóa một đối tượng Document để thu được một mảng byte và sau đó cách hủy tuần tự hóa mảng byte để lấy lại đối tượng Document:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); | |
// Load the document from disk. | |
Document doc = new Document(dataDir + "Test File (doc).doc"); | |
// Create a new memory stream. | |
MemoryStream outStream = new MemoryStream(); | |
// Save the document to stream. | |
doc.Save(outStream, SaveFormat.Docx); | |
// Convert the document to byte form. | |
byte[] docBytes = outStream.ToArray(); | |
// The bytes are now ready to be stored/transmitted. | |
// Now reverse the steps to load the bytes back into a document object. | |
MemoryStream inStream = new MemoryStream(docBytes); | |
// Load the stream into a new document object. | |
Document loadDoc = new Document(inStream); |
Bạn có thể tải xuống tệp mẫu của ví dụ này từ Aspose.Words GitHub.
Lưu trữ, đọc và xóa tài liệu trong cơ sở dữ liệu
Phần này trình bày cách lưu tài liệu trong cơ sở dữ liệu rồi tải lại vào đối tượng Document
để làm việc với nó. Để đơn giản, tên tệp là khóa dùng để lưu trữ và tìm nạp tài liệu từ cơ sở dữ liệu. Cơ sở dữ liệu chứa hai cột. Cột đầu tiên “Tên tệp” được lưu dưới dạng Chuỗi và được sử dụng để xác định tài liệu. Cột thứ hai “FileContent” được lưu trữ dưới dạng đối tượng BLOB
lưu trữ đối tượng tài liệu ở dạng byte.
Ví dụ mã sau đây cho thấy cách thiết lập kết nối tới cơ sở dữ liệu và thực thi các lệnh:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
string dbName = ""; | |
// Open a database connection. | |
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + RunExamples.GetDataDir_Database() + dbName; | |
OleDbConnection mConnection = new OleDbConnection(connString); | |
mConnection.Open(); |
Ví dụ về mã sau đây cho biết cách lưu tài liệu vào cơ sở dữ liệu, sau đó đọc lại cùng một tài liệu và cuối cùng xóa bản ghi chứa tài liệu khỏi cơ sở dữ liệu:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// Store the document to the database. | |
StoreToDatabase(doc, mConnection); | |
// Read the document from the database and store the file to disk. | |
Document dbDoc = ReadFromDatabase(fileName, mConnection); | |
// Save the retrieved document to disk. | |
string newFileName = Path.GetFileNameWithoutExtension(fileName) + " from DB" + Path.GetExtension(fileName); | |
dbDoc.Save(dataDir + newFileName); | |
// Delete the document from the database. | |
DeleteFromDatabase(fileName, mConnection); | |
// Close the connection to the database. | |
mConnection.Close(); |
Lưu tài liệu vào cơ sở dữ liệu
Để lưu tài liệu trong cơ sở dữ liệu, hãy chuyển đổi tài liệu này thành một mảng byte, như được mô tả ở đầu bài viết này. Sau đó, lưu mảng byte này vào trường cơ sở dữ liệu.
Ví dụ mã sau đây cho thấy cách lưu tài liệu vào cơ sở dữ liệu đã chỉ định:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
public static void StoreToDatabase(Document doc, OleDbConnection mConnection) | |
{ | |
// Save the document to a MemoryStream object. | |
MemoryStream stream = new MemoryStream(); | |
doc.Save(stream, SaveFormat.Docx); | |
// Get the filename from the document. | |
string fileName = Path.GetFileName(doc.OriginalFileName); | |
// Create the SQL command. | |
string commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + fileName + "', @Docx)"; | |
OleDbCommand command = new OleDbCommand(commandString, mConnection); | |
// Add the @Docx parameter. | |
command.Parameters.AddWithValue("Docx", stream.ToArray()); | |
// Write the document to the database. | |
command.ExecuteNonQuery(); | |
} |
Chỉ định commandString, đây là một biểu thức SQL thực hiện tất cả công việc:
- Để lưu tài liệu vào cơ sở dữ liệu, lệnh “INSERT INTO” được sử dụng và một bảng được chỉ định cùng với các giá trị của hai trường bản ghi – FileName và FileContent. Để tránh các tham số bổ sung, tên tệp được lấy từ chính đối tượng Document. Giá trị trường
FileContent
được gán byte từ luồng bộ nhớ, chứa biểu diễn nhị phân của tài liệu được lưu trữ. - Dòng mã còn lại thực hiện lệnh lưu trữ tài liệu Aspose.Words vào cơ sở dữ liệu.
Truy xuất tài liệu từ cơ sở dữ liệu
Để truy xuất tài liệu từ cơ sở dữ liệu, hãy chọn bản ghi chứa dữ liệu tài liệu dưới dạng mảng byte. Sau đó tải mảng byte từ bản ghi vào MemoryStream và tạo đối tượng Document sẽ tải tài liệu từ MemoryStream.
Ví dụ về mã sau đây cho thấy cách truy xuất và trả về một tài liệu từ cơ sở dữ liệu đã chỉ định bằng cách sử dụng tên tệp làm khóa để tìm nạp tài liệu này:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
public static Document ReadFromDatabase(string fileName, OleDbConnection mConnection) | |
{ | |
// Create the SQL command. | |
string commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'"; | |
OleDbCommand command = new OleDbCommand(commandString, mConnection); | |
// Create the data adapter. | |
OleDbDataAdapter adapter = new OleDbDataAdapter(command); | |
// Fill the results from the database into a DataTable. | |
DataTable dataTable = new DataTable(); | |
adapter.Fill(dataTable); | |
// Check there was a matching record found from the database and throw an exception if no record was found. | |
if (dataTable.Rows.Count == 0) | |
throw new ArgumentException(string.Format("Could not find any record matching the document \"{0}\" in the database.", fileName)); | |
// The document is stored in byte form in the FileContent column. | |
// Retrieve these bytes of the first matching record to a new buffer. | |
byte[] buffer = (byte[])dataTable.Rows[0]["FileContent"]; | |
// Wrap the bytes from the buffer into a new MemoryStream object. | |
MemoryStream newStream = new MemoryStream(buffer); | |
// Read the document from the stream. | |
Document doc = new Document(newStream); | |
// Return the retrieved document. | |
return doc; | |
} |
Xóa tài liệu khỏi cơ sở dữ liệu
Để xóa tài liệu khỏi cơ sở dữ liệu, hãy sử dụng lệnh SQL thích hợp mà không cần bất kỳ thao tác nào trên đối tượng Document.
Ví dụ về mã sau đây cho biết cách xóa tài liệu khỏi cơ sở dữ liệu bằng cách sử dụng tên tệp để tìm nạp bản ghi:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
public static void DeleteFromDatabase(string fileName, OleDbConnection mConnection) | |
{ | |
// Create the SQL command. | |
string commandString = "DELETE * FROM Documents WHERE FileName='" + fileName + "'"; | |
OleDbCommand command = new OleDbCommand(commandString, mConnection); | |
// Delete the record. | |
command.ExecuteNonQuery(); | |
} |