首先你要知道的是 SqlDataReader 是不能保存数据的,她是只读的。

解决方案 »

  1.   

    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Text;
    using System.IO;
    using System.Data;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary; private void button1_Click(object sender, System.EventArgs e)
    {
    Point myPoint; // Initialize:
    myPoint.x = 10;
    myPoint.y = 20; IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
    formatter.Serialize(stream, myPoint);

    stream.Close(); System.IO.FileStream fs =new FileStream("MyFile.bin",System.IO.FileMode.Open);
               
    byte []byts=new byte[fs.Length] ;
    fs.Read(byts, 0,(int) fs.Length);
    fs.Close(); SqlConnection conn=new SqlConnection(Tools.strConn);
    SqlCommand mycom=new SqlCommand("update table1 set struct=@struct where id=@ID",conn);
    mycom.CommandType=System.Data.CommandType.Text; mycom.Parameters.Add(new SqlParameter("@ID",System.Data.SqlDbType.Int));
    mycom.Parameters["@ID"].Value=1;    mycom.Parameters.Add(new SqlParameter("@struct",System.Data.SqlDbType.Image));
    mycom.Parameters["@struct"].Value=byts;  try

    conn.Open();
    mycom.ExecuteNonQuery();

    }
    catch(Exception ex)
    {
    throw new Exception(ex.Message,ex);
    }
    finally
    {
    mycom.Dispose();
    conn.Dispose();
    }

    } private void button2_Click(object sender, System.EventArgs e)
    {

    SqlConnection conn=new SqlConnection(Tools.strConn);
    SqlCommand mycom=new SqlCommand("select struct from table1 where id=@ID",conn);
    mycom.CommandType=System.Data.CommandType.Text; mycom.Parameters.Add(new SqlParameter("@ID",System.Data.SqlDbType.Int));
    mycom.Parameters["@ID"].Value=1; 
    SqlDataReader dr=null;

    try

    conn.Open();
    dr=mycom.ExecuteReader();
    if(dr.Read())
    {
    Byte[] byts = new  byte[(dr.GetBytes(0, 0, null, 0, int.MaxValue))];
    dr.GetBytes(0, 0, byts, 0, byts.Length);
    System.IO.FileStream fs =
    new System.IO.FileStream("MyFile.bin", System.IO.FileMode.Create, System.IO.FileAccess.Write); fs.Write(byts, 0, byts.Length);
    fs.Close();
    }


    }
    catch(Exception ex)
    {
    throw new Exception(ex.Message,ex);
    }
    finally
    {
    mycom.Dispose();
    conn.Dispose();
    }
    IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
    Point myPoint = (Point) formatter.Deserialize(stream);
    stream.Close();
    Console.WriteLine(myPoint.x.ToString());
    Console.WriteLine(myPoint.y.ToString()); } [Serializable]
    public struct Point 
    {
    public int x, y; public Point(int x, int y) 
    {
    this.x = x;
    this.y = y; 
    }
    }