Serialize ולעבוד עם מסמך במסד נתונים

אחת המשימות שאתה יכול לעשות כאשר עבודה עם מסמכים היא אחסון ושיקום Document אובייקטים וממסד נתונים. לדוגמה, זה יהיה הכרחי אם תיישם כל סוג של מערכת ניהול תוכן. יש לאחסן את כל הגרסאות הקודמות של המסמכים במערכת מסד הנתונים. היכולת לאחסן מסמכים במסד הנתונים היא גם שימושית ביותר כאשר היישום שלך מספק שירות מבוסס אינטרנט.

Aspose.Words מספק יכולת להמיר מסמך למערך ע"י דואר עבור עבודה לאחר מכן עם מסמך זה במסד נתונים.

עקבו אחרי Byte Array

כדי לאחסן מסמך במסד נתונים או להכין מסמך לשידור ברחבי האינטרנט, לעתים קרובות יש צורך לקבוע את המסמך כדי להשיג מערך עוטה.

כדי לנסח Document אובייקט Aspose.Words:

1.1 1. להציל אותו ל MemoryStream באמצעות Save המונחים: overload Document מעמד. 1.1 1. התקשר ToArray שיטה, אשר מחזירה מערך של עיתות המייצגות את המסמך בצורה עוטה.

השלבים לעיל ניתן להפוך כדי לטעון את המטות בחזרה לתוך a Document אובייקט.

הדוגמה הבאה מראה כיצד לארגן Document להתנגד להשגת מערך עוטה, ולאחר מכן כיצד להשבית את מערך ה- Byte כדי להשיג מערך 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);

ניתן להוריד את קובץ התבנית של דוגמה זו Aspose.Words GitHub.

קרא ומחק מסמך במסד נתונים

סעיף זה מראה כיצד לשמור מסמך במסד נתונים ולאחר מכן לטעון אותו בחזרה לתוך מסד נתונים. Document להתנגד לעבוד איתו. לשם הפשטות, שם הקובץ הוא המפתח המשמש לאחסון ולמשוך מסמכים ממסד הנתונים. מסד הנתונים מכיל שני עמודים. העמודה הראשונה “File Name” מאוחסנת כ String ומשמשת לזיהוי מסמכים. העמודה השנייה “Filecontent” מאוחסנת כעמוד BLOB אובייקט אשר מאחסן את אובייקט המסמך בצורה עוטה.

דוגמה הקוד הבא מראה כיצד להגדיר חיבור למסד נתונים ולבצע פקודות:

// 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();

הדוגמה הבאה של הקוד מראה כיצד לחסוך מסמך למסד הנתונים, ואז לקרוא את אותו מסמך שוב, ולבסוף למחוק את הרשומה המכילה את המסמך ממסד הנתונים:

// 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();

שמור מסמך למסד נתונים

כדי לשמור מסמך במסד נתונים להמיר מסמך זה למערך של עציצים, כפי שתואר בתחילת מאמר זה. לאחר מכן, שמור את מערך התווך הזה לתחום מסד נתונים.

הדוגמה הבאה של הקוד מראה כיצד לחסוך מסמך למסד הנתונים שצוין:

// 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();
}

הוראות ספציפיות, שהוא ביטוי של SQL שעושה את כל העבודה:

    • כדי לשמור מסמך לתוך מסד הנתונים, הפקודה “INSERT INTO” משמשת ושולחן שצוין יחד עם הערכים של שני שדות שיא - שם קובץ ו- Filecontent. כדי למנוע פרמטרים נוספים, שם הקובץ נלקח מן Document להתנגד לעצמו. The The The FileContent ערך שדה מוקצה על ידיות מן זרם הזיכרון, המכיל ייצוג בינארי של המסמך המאוחסן.
    • קו הקוד הנותרים מבצע את הפקודה אשר מאחסנת את הפקודה Aspose.Words מסמך במסד הנתונים.

החזרת מסמך ממסד נתונים

כדי לאחזר מסמך ממסד הנתונים, בחר את הרשומה המכילה את נתוני המסמך כמערך של עקיפים. לאחר מכן לטעון את מערך התווך מן השיא לתוך MemoryStream ליצור Document אובייקט שיטען את המסמך מן MemoryStream.

הדוגמה הבאה של הקוד מראה כיצד לשחזר ולהחזיר מסמך ממסד הנתונים שצוין באמצעות שם הקובץ כמפתח להביא מסמך זה:

// 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;
}

למחוק מסמך ממסד נתונים

כדי למחוק מסמך ממסד הנתונים, השתמש בפקד SQL המתאים ללא כל מניפולציה על Document אובייקט.

לדוגמה הקוד הבא מראה כיצד למחוק מסמך ממסד הנתונים, באמצעות שם הקובץ כדי להביא את הרשומה:

// 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();
}