分享

实例:如何用C#读写数据库Image字段

 丑的不明显 2010-10-28
实例:如何用C#读写数据库Image字段
 1、数据库Image字段读写文件

    写文件:写文件的过程为将文件以流文件形式打开并将内容读取到一个byte数组,然后将此byte数组写入数据库的Image字段。

    源码:
    FileInfo finfo=new FileInfo("文件名");  //绝对路径
    if(finfo.Exists)
    {
        SqlConnection conn=new SqlConnection("连接字符串");
        SqlCommand InsertCommand=new SqlCommand();
        InsertCommand.Connection=conn;
        InsertCommand.CommandText="Insert into 表名(Image字段名) values(@Content)";
        InsertCommand.Parameters.Add("@Content",SqlDbType.Image,(int)finfo.Length,"Image字段名");   //注意,此处参数Size为写入的字节数 
        //读取文件内容,写入byte数组
        byte[] content=new byte[finfo.Length];
        FileStream stream=finfo.OpenRead();
        stream.Read(content,0,content.Length);
        stream.Close();
        InsertCommand.Parameters["@Content"].Value=content;  //为参数赋值
        try
        {
            conn.Open();
            InsertCommand.ExcuteNonQuery();
        }
        finally
        { 


            conn.Close();
        }
    }
    
    读文件:读文件的过程为从数据库的Image字段读取内容保存到byte数组,然后将此byte数组以文件流形式写入文件。
    
    源码:
    byte[] content;
    SqlConnetion conn=new SqlConnection("连接字符串");
    SqlDataAdapter da=new SqlDataAdapter("Select Image字段名 from 表名",conn);
    DataSet ds=new DataSet();
    da.Fill(da,"word");
    DataRow dr=ds.Tables["word"].Rows[0];    //将读取的第一行内容保存到dr
    
    content=(byte[])dr["Image字段名"]; 
    int ArraySize=content.GetUpperBound(0);
    FileStream stream=new FileStream("文件名",FileMode.OpenOrCreate,FileAccess.Write);
    stream.Write(content,0,ArraySize);
    stream.Close();
    
    2、数据库Image字段读写图片

    绑定到控件的方式:
     通过将Image字段绑定到PictureBox实现。文件中我提供了一个实例,要正常运行需要在Northwind中添加数据库表Employees, 数据库表的结构为EmployeeID Int(4) 自动增长,FirstName nvarchar(10),LastName nvarchar (20),Photo image(16) null。

    直接用SqlCommand实现:
    其实把握住Image 字段存的是byte类型数据,用SqlCommand实现添加、修改就很简单了,跟文本的区别就是在读出的时候需要将byte类型数据转化为Image图 片,在写入时需要将Image图片以流的形式转为为byte数组,然后再将byte数组保存到Image字段。 
    实例:
           comm = "Insert into MyEmployees(FirstName,LastName,Photo) values(@FName,@LName,@Photo)";
           SqlCommand command=new SqlCommand(comm);
           command.Connection = conn;
           //创建Parameter
           command.Parameters.Add("@FName",SqlDbType.NVarChar);
           command.Parameters[0].Value = textBox1.Text;
           command.Parameters.Add("@LName", SqlDbType.NVarChar);
           command.Parameters[1].Value = textBox2.Text; 
           command.Parameters.Add("@Photo",SqlDbType.Image);
           command.Parameters[2].Value = imgByte;
    其中imgByte为Byte数组,通过FileStream的Read填充的byte数据。
实例:如何用C#读写数据库Image字段


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多