C # Access SQL Server database two: Using serialization for class linked list access (Arraylist,varbina

Source: Internet
Author: User
Tags serialization

Create a project

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

A. uniquely identifies the field name is "ID"and the type is Int.

B. a field of type VarChar called "Description" with a field length of

c. A field of type varbinary (Max) called "Data" .

2. start visual Studio. NET and create a new Visual C # Window S Application project.

3. Drag two Button controls from the toolbar to the default form, Form1 .

4. in the Properties window, modify Name buttonfiletodb, Text property is saved to the database from the file, and then the Name is modified to buttondbtofile , the Text property is saved to a file from the database .

SOURCE Example

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

using System.IO;

using System.Collections;

using System.Runtime.Serialization.Formatters.Binary;

// Database Description: MyTest database, rwtest Table , contains 3 columns: ID (int), Description (varchar), Data (varbinary (max))

namespace Rwarraylistsql

{

public partial class Form1 : Form

    {

ArrayList ArrayList = new ArrayList();

public Form1 ()

        {

InitializeComponent ();

for (int i = 0; i < i++)

            {

ptdata ptdata = new ptdata();

Ptdata.ptid = i + 1;

ptdata.ptname = Convert. ToString (i + 1);

Ptdata.pt_data = i + 1;

Arraylist.add (ptdata);

            }

        }

private void Buttonfiletodb_click (object sender, EventArgs E

        {

SqlConnection SqlConnection = new SqlConnection("Data Source=liuxu Eqin;initial catalog=mytest;integrated security=true ");                

SqlDataAdapter sqldataadapter = New SqlDataAdapter ( "SELECT * from Rwtest", SqlConnection);

sqlcommandbuilder sqlcommandbuilder = new SqlCommandBuilder(Sqldataada Pter);

System.Data. DataSet DataSet = new DataSet("rwtest");

sqldataadapter.missingschemaaction = MissingSchemaAction. AddWithKey; // Identify existing DataSet the action to perform if the schema does not match the incoming data.

                // Define a stream

Stream stream = new MemoryStream();

                // Define a formatter

binaryformatter bf = new BinaryFormatter();

foreach (object obj in arrayList)

                {

BF. Serialize (stream, obj); // serialization

                }

byte[] array = null;

array = new byte[stream. Length];

                // to write a binary stream to an array

Stream. Position = 0;

Stream. Read (array, 0, (int) stream. Length);

                // Close the stream

Stream. Close ();

try

            {

Sqldataadapter.fill (DataSet, "Rwtest");

//datarow represents a row of data in a DataTable

System.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 to database success!") ", " Information tips , messageboxbuttons. OK, MessageBoxIcon. Information);

            }

Catch (Exception ex)

            {

If (sqlconnection.state = = ConnectionState. Open)

                {

sqlconnection.close ();

                }

MessageBox. Show ( Write database failed )+ex. Message, " informational hint ", messageboxbuttons. OK, MessageBoxIcon. ERROR);

            }

        }

private void Buttondbtofile_click (object sender, EventArgs E

        {

SqlConnection SqlConnection = new SqlConnection("Data Source=liuxueqin ; Initial catalog=mytest;integrated security=true ");

SqlDataAdapter SqlDataAdapter = new SqlDataAdapter("SELECT * From Rwtest ", SqlConnection);

sqlcommandbuilder sqlcommandbuilder = new SqlCommandBuilder(SqlDataAdapter );

DataSet DataSet = new DataSet("rwtest");

Sqldataadapter.fill (DataSet, "Rwtest");

DataRow myrow;

myrow = dataset.tables["Rwtest"]. Rows[0];

byte [] b = null;

B = (byte[]) myrow["Data"];

            // Define a stream

MemoryStream stream = new MemoryStream(b);

            // Define a formatter

binaryformatter bf = new BinaryFormatter();            

while (stream. Position!= Stream. Length)

            {

Arraylist.add (BF. Deserialize (stream)); // deserialization

            }

Stream. Close ();

for (int i=0;i<5;i++) // Informational prompt, is the correct removal of the ARRA from the database Ylist Linked list

MessageBox. Show (((ptdata) arraylist[i]). Ptname, " Information tips ", messageboxbuttons. OK, MessageBoxIcon. Information);

If (sqlconnection.state = = ConnectionState. Open)

            {

sqlconnection.close ();

            }

MessageBox. Show (" read data from database success!") ", " Information tips , messageboxbuttons. OK, MessageBoxIcon. Information);

        }

}

// added attributes on top of class: Serializable. ( If you do not add this property , will throw SerializationException Exception ). Without inheriting from the interface ISerializable , you can allow the class to be serialized by adding the [Serializable] property.

[Serializable]

class ptdata

    {

public ptdata ()

        {

Ptid = 1;

ptname = "None";

Pt_data = 1.0;

        }

public int Ptid;

public string ptname;

public double Pt_data;

    }

}







</

Related Article

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.