How to serialize a class and store it directly into a database

Source: Internet
Author: User
Tags serialization

Reference Code 1

You can use the serialization and deserialization methods provided by the. NET to serialize the object into an XML string and then into the database, when you want to use the object, You can then deserialize the saved string in the database into an object, and the following is the sample code:

 Public classcat{ Public stringColor {Get;Set; }  Public intSpeed {Get;Set; }  Public stringname{Get;Set; } }//Serialization ofvarcat1=NewCat{color="Write", speed= -, name="MiMi" }; XmlSerializer ser=NewXmlSerializer (typeof(Cat)); MemoryStream Ms=NewMemoryStream (); Ser. Serialize (MS, CAT1);stringXMLString =Encoding.UTF8.GetString (Ms. ToArray ());//xmlstring is the string you want to save to the database//deserializationXmlSerializer Dser =NewXmlSerializer (typeof(Cat));//xmlstring is the string you get from the databaseStream Xmlstream =NewMemoryStream (Encoding.UTF8.GetBytes (xmlstring)); Cat Cat2=dser. Deserialize (Xmlstream) asCat;//Cat2 is the class object you're going to get.

Reference Code 2

Create a project

1. Add a table named Rwtest to the SQL Server MYTest database. The table field is set as follows:

A. The unique identity field name is "ID" and the type is int.

B. A varchar-type field named "Description" with a field length of 50.

C. A field of type varbinary (MAX) with the name "Data".

2. Start visual Studio. NET and create a new Visual C # Windows application project.

3. Drag a two button control from the toolbar to the default form, Form1.

4. In the Properties window, modify name to Buttonfiletodb, the Text property to save from file to database, then modify name to Buttondbtofile, and the Text property to save from database to file.

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Data.SqlClient;usingSystem.IO;usingSystem.Collections;usingSystem.Runtime.Serialization.Formatters.Binary; //Database Description: mytest database, Rwtest table, containing 3 columns: ID (int), Description (varchar), Data (varbinary (max))  namespacerwarraylistsql{ Public Partial classform1:form {ArrayList ArrayList=NewArrayList ();  PublicForm1 () {InitializeComponent ();  for(inti =0; I < -; i++) {ptdata ptdata=Newptdata (); Ptdata.ptid= i +1; Ptdata.ptname= convert.tostring (i +1); Ptdata.pt_data= i +1;            Arraylist.add (ptdata); }         }          Private voidButtonfiletodb_click (Objectsender, EventArgs e) {SqlConnection SqlConnection=NewSqlConnection ("Data source=liuxueqin;initial catalog=mytest;integrated security=true"); SqlDataAdapter SqlDataAdapter=NewSqlDataAdapter ("Select * from Rwtest", sqlConnection); SqlCommandBuilder SqlCommandBuilder=NewSqlCommandBuilder (SqlDataAdapter); System.Data.DataSet DataSet=NewDataSet ("rwtest"); Sqldataadapter.missingschemaaction= MissingSchemaAction.AddWithKey;//determines what needs to be done if the existing dataset schema does not match the incoming data. //Define a flowStream stream =NewMemoryStream (); //Define a formatterBinaryFormatter BF =NewBinaryFormatter (); foreach(ObjectObjincharrayList) {BF.  Serialize (stream, obj); //Serialization of                }                byte[] Array =NULL; Array=New byte[Stream.                Length]; //writes a binary stream to an arrayStream. Position =0; Stream. Read (Array,0, (int) stream.                Length); //Close the streamStream.              Close (); Try{Sqldataadapter.fill (DataSet,"rwtest"); //DataRow represents a row of data in a DataTableSystem.Data.DataRow DataRow1; DataRow1= dataset.tables["rwtest"].                NewRow (); datarow1["ID"] =1; datarow1["Description"] ="This would is description text"; datarow1["Data"] =Array; dataset.tables["rwtest"].                Rows.Add (DATAROW1); Sqldataadapter.update (DataSet,"rwtest");                Sqlconnection.close (); MessageBox.Show ("Write Database Success! ","Information Tips", MessageBoxButtons.OK, messageboxicon.information); }            Catch(Exception ex) {if(Sqlconnection.state = =ConnectionState.Open) {sqlconnection.close (); } MessageBox.Show ("failed to write to database"+ex. Message,"Information Tips", MessageBoxButtons.OK, Messageboxicon.error); }        }          Private voidButtondbtofile_click (Objectsender, EventArgs e) {SqlConnection SqlConnection=NewSqlConnection ("Data source=liuxueqin;initial catalog=mytest;integrated security=true"); SqlDataAdapter SqlDataAdapter=NewSqlDataAdapter ("Select * from Rwtest", sqlConnection); SqlCommandBuilder SqlCommandBuilder=NewSqlCommandBuilder (SqlDataAdapter); DataSet DataSet=NewDataSet ("rwtest"); Sqldataadapter.fill (DataSet,"rwtest");            DataRow Myrow; Myrow= dataset.tables["rwtest"]. rows[0]; byte[] B =NULL; b= (byte[]) myrow["Data"]; //Define a flowMemoryStream stream =NewMemoryStream (b); //Define a formatterBinaryFormatter BF =NewBinaryFormatter ();  while(Stream. Position! =Stream. Length) {Arraylist.add (BF.  Deserialize (stream)); //deserialization} stream.             Close ();  for(intI=0;i<5; i++)//information Tip, whether the ArrayList linked list was removed correctly from the databaseMessageBox.Show (((ptdata) arraylist[i]). Ptname,"Information Tips", MessageBoxButtons.OK, messageboxicon.information); if(Sqlconnection.state = =ConnectionState.Open) {sqlconnection.close (); } MessageBox.Show ("read the data from the database successfully! ","Information Tips", MessageBoxButtons.OK, messageboxicon.information); } }      //added attribute on top of class: Serializable. (If you do not add this property, the SerializationException exception will be thrown). Without inheriting from the interface ISerializable, you can allow the class to be serialized by adding the [Serializable] property. [Serializable]classptdata { Publicptdata () {PTID=1; Ptname="None"; Pt_data=1.0; }         Public intPTID;  Public stringPtname;  Public DoublePt_data; }}

Reference articles

z_y8008, C # How to store objects of a class in a database

Crazy Coder, C # Implementation stores a class serialization in a database

How to serialize a class and store it directly into a database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.