原文 Storing and Retrieving Images from SQL Server using Microsoft .NET

Introduction

This article is about storing and retrieving images from database in Microsoft .NET using C#.

Tools Used

  • SQL Server 2000
  • Microsoft .NET Version 1.1
  • C# (Windows Forms based application)

Storing Images

  1. Create a table in a SQL Server 2000 database which has at least one field of type IMAGE.

    Here is the script I used:

     Collapse | Copy Code
    CREATE TABLE [dbo].[tblImgData] (
    
            [ID] [int] NOT NULL ,
    
            [Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    
            [Picture] [image] NULL 
    
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  2. Actually IMAGE field is just holding the reference to the page containing the binary data so we have to convert our image into bytes.
    1. I used a file open dialog box to locate the file.

       Collapse | Copy Code
      this.openFileDialog1.ShowDialog(this);
      string strFn=this.openFileDialog1.FileName;
    2. By using FileInfo class, I retrieved the file size:
       Collapse | Copy Code
      FileInfo fiImage=new FileInfo(strFn);
    3. Declare an array of that size.
       Collapse | Copy Code
      this.m_lImageFileLength=fiImage.Length;
      m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)];
    4. By using FileStream object, I filled the byte array.
       Collapse | Copy Code
      FileStream fs=new FileStream(strFn,FileMode.Open,
      FileAccess.Read,FileShare.Read);
      int iBytesRead=fs.Read(m_barrImg,0,
      Convert.ToInt32(this.m_lImageFileLength));
      fs.Close();

    Complete Load Image Code

     Collapse | Copy Code
    protected void LoadImage()
    {
    try
    {
    this.openFileDialog1.ShowDialog(this);
    string strFn=this.openFileDialog1.FileName;
    this.pictureBox1.Image=Image.FromFile(strFn);
    FileInfo fiImage=new FileInfo(strFn);
    this.m_lImageFileLength=fiImage.Length;
    FileStream fs=new FileStream(strFn,FileMode.Open,
    FileAccess.Read,FileShare.Read);
    m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)];
    int iBytesRead = fs.Read(m_barrImg,0,
    Convert.ToInt32(this.m_lImageFileLength));
    fs.Close();
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
  3. Saving byte array data to database.
    1. Create command text to insert record.

       Collapse | Copy Code
      this.sqlCommand1.CommandText=
      "INSERT INTO tblImgData(ID,Name,Picture)" +
      " values(@ID,@Name,@Picture)";
    2. Create parameters.
       Collapse | Copy Code
      this.sqlCommand1.Parameters.Add("@ID",
      System.Data.SqlDbType.Int, 4);
      this.sqlCommand1.Parameters.Add("@Name",
      System.Data.SqlDbType.VarChar, 50); this.sqlCommand1.Parameters.Add("@Picture",
      System.Data.SqlDbType.Image);

      Notice “@Picture” has “SqlDbType.Image” because it is of IMAGE type Field.

    3. Provide the value to the parameters.
       Collapse | Copy Code
      this.sqlCommand1.Parameters["@ID"].Value=this.editID.Text;
      this.sqlCommand1.Parameters["@Name"].Value=this.editName.Text; this.sqlCommand1.Parameters["@Picture"].Value=this.m_barrImg;

      this.m_barrImg” is a byte array which we filled in the previous step.

    4. Now execute non-query for saving the record to the database.
       Collapse | Copy Code
      int iresult=this.sqlCommand1.ExecuteNonQuery();

    Complete Save Image Code

     Collapse | Copy Code
    private void btnSave_Click(object sender, System.EventArgs e)
    {
    try
    {
    this.sqlConnection1.Open();
    if (sqlCommand1.Parameters.Count ==0 )
    {
    this.sqlCommand1.CommandText="INSERT INTO tblImgData(ID," +
    " Name,Picture) values(@ID,@Name,@Picture)";
    this.sqlCommand1.Parameters.Add("@ID",
    System.Data.SqlDbType.Int,4);
    this.sqlCommand1.Parameters.Add("@Name",
    System.Data.SqlDbType.VarChar,50);
    this.sqlCommand1.Parameters.Add("@Picture",
    System.Data.SqlDbType.Image);
    } this.sqlCommand1.Parameters["@ID"].Value=this.editID.Text;
    this.sqlCommand1.Parameters["@Name"].Value=this.editName.Text;
    this.sqlCommand1.Parameters["@Picture"].Value=this.m_barrImg; int iresult=this.sqlCommand1.ExecuteNonQuery();
    MessageBox.Show(Convert.ToString(iresult));
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    finally
    {
    this.sqlConnection1.Close();
    }
    }

Retrieving Image

Retrieving images from the database is the exact reverse process of saving images to the database.

  1. First create command text to retrieve record.

     Collapse | Copy Code
    SqlCommand cmdSelect = new SqlCommand("select Picture" +
    " from tblImgData where ID=@ID",
    this.sqlConnection1);
  2. Create parameter for the query.
     Collapse | Copy Code
    cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
  3. Provide value to the parameter.
     Collapse | Copy Code
    cmdSelect.Parameters["@ID"].Value=this.editID.Text;
  4. Open database connection and execute “ExecuteScalar” because we want only “IMAGE” column data back.
     Collapse | Copy Code
    byte[] barrImg=(byte[])cmdSelect.ExecuteScalar();

    As the execute scalar returns data of “Object” data type, we cast it to byte array.

  5. Save this data to a temporary file.
     Collapse | Copy Code
    string strfn=Convert.ToString(DateTime.Now.ToFileTime());
    FileStream fs=new FileStream(strfn,FileMode.CreateNew,FileAccess.Write);
    fs.Write(barrImg,0,barrImg.Length);
    fs.Flush();
    fs.Close();
  6. And display the image anywhere you want to display.
     Collapse | Copy Code
    pictureBox1.Image=Image.FromFile(strfn);

Complete Image Retrieving Code

 Collapse | Copy Code
private void btnLoad_Click(object sender, System.EventArgs e)
{
try
{
SqlCommand cmdSelect=new SqlCommand("select Picture" +
" from tblImgData where ID=@ID",this.sqlConnection1);
cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
cmdSelect.Parameters["@ID"].Value=this.editID.Text; this.sqlConnection1.Open();
byte[] barrImg=(byte[])cmdSelect.ExecuteScalar();
string strfn=Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs=new FileStream(strfn,
FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg,0,barrImg.Length);
fs.Flush();
fs.Close();
pictureBox1.Image=Image.FromFile(strfn);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.sqlConnection1.Close();
}
}

Bibliography

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Storing and Retrieving Images from SQL Server using Microsoft .NET的更多相关文章

  1. 转载:Character data is represented incorrectly when the code page of the client computer differs from the code page of the database in SQL Server 2005

    https://support.microsoft.com/en-us/kb/904803 Character data is represented incorrectly when the cod ...

  2. SQL SERVER 2012/2014 链接到 SQL SERVER 2000的各种坑

    本文总结一下SQL SERVER 2012/2014链接到SQL SERVER 2000的各种坑,都是在实际应用中遇到的疑难杂症.可能会有人说怎么还在用SQL SERVER 2000,为什么不升级呢? ...

  3. SQL SERVER 2005删除维护作业报错:The DELETE statement conflicted with the REFERENCE constraint "FK_subplan_job_id"

    案例环境: 数据库版本: Microsoft SQL Server 2005 (Microsoft SQL Server 2005 - 9.00.5000.00 (X64) ) 案例介绍: 对一个数据 ...

  4. [转]SQL SERVER – Importance of Database Schemas in SQL Server

    原文地址http://blog.sqlauthority.com/2009/09/07/sql-server-importance-of-database-schemas-in-sql-server/ ...

  5. sql server数据库连接问题处理

    下面请一字一句地看,一遍就设置成功,比你设置几十遍失败,费时会少得多. 首先,在连接数据库之前必须保证SQL Server 2012是采用SQL Server身份验证方式而不是windows身份验证方 ...

  6. Sql Server 2008卸载后再次安装一直报错

    sql server 2008卸载之后再次安装一直报错问题. 第一:由于上一次的卸载不干净,可参照百度完全卸载sql server2008 的方式 1. 用WindowsInstaller删除所有与S ...

  7. [转载]在SQL Server 中,如何实现DBF文件和SQL Server表之间的导入或者导出?

    原来使用SQL Server 2000数据库,通过DTS工具很方便地在SQL Server和DBF文件之间进行数据的导入和导出,现在安装了SQL Server2005之后,发现其提供的“SQL Ser ...

  8. sql server 基础教程[温故而知新三]

    子曰:“温故而知新,可以为师矣.”孔子说:“温习旧知识从而得知新的理解与体会,凭借这一点就可以成为老师了.“ 尤其是咱们搞程序的人,不管是不是全栈工程师,都是集十八般武艺于一身.不过有时候有些知识如果 ...

  9. 招聘 微软全球技术支持中心 sql server组

    微软亚太区全球技术支持中心(APGC CSS)是微软为个人用户.开发者.IT 专业人员到合作伙伴和企业级合作伙伴提供全方位.多元化的服务和技术支持的部门.一个优秀的SQL Server技术支持工程师应 ...

随机推荐

  1. Windows上的的神技

    Windows上的的神技 不用借助任何第三方软件,其实Windows也大有可为——比你目前了解得至少要多得多,强大技能快来get起来! 1.文件隐藏谁的电脑里没点小秘密?东藏西藏到最后自己都找不到了有 ...

  2. C# Windows Phone 8 WP8 高级开发,制作不循环 Pivot ,图片(Gallery)导览不求人! 内附图文教学!!

    原文:C# Windows Phone 8 WP8 高级开发,制作不循环 Pivot ,图片(Gallery)导览不求人! 内附图文教学!! 一般我们在开发Winodws Phone APP 的时候往 ...

  3. 【Android进阶】Gson解析json字符串的简单应用

    在客户端与服务器之间进行数据传输,一般采用两种数据格式,一种是xml,一种是json.这两种数据交换形式各有千秋,比如使用json数据格式,数据量会比较小,传输速度快,放便解析,而采用xml数据格式, ...

  4. 使用cm-12.0源代码编译twrp

    Select the newest branch available. This step is not necessary with Omni because Omni already includ ...

  5. Linux高性能server规划——多进程编程

    多进程编程 多进程编程包含例如以下内容: 复制进程影映像的fork系统调用和替换进程映像的exec系列系统调用. 僵尸进程以及怎样避免僵尸进程 进程间通信(Inter-Process Communic ...

  6. ASP.NET执行循序

    首先第一次运行一个应用程序(WebSite或者WebApplication都是Web应用程序)第一次请求 -> 1,IIS -> 2,aspnet_isapi(非托管dll) -> ...

  7. Swift语法学习之 类和结构体

    类和结构体 本页包括内容: 类和结构体对照 结构体和枚举是值类型 类是引用类型 类和结构体的选择 集合(collection)类型的赋值与复制行为 与其他编程语言所不同的是,Swift 并不要求你为自 ...

  8. hdu 1429 胜利大逃亡(延续)(BFS+比特压缩)

    #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm& ...

  9. 从一开始,说出事java匿名内部类

    java内部类.匿名类原本以为它们的使用已经很滑, 成绩, 就在昨天晚上12指向时钟发生重大事故.事故的严重程度再说吧,那是因为我没有睡一晚睡眠. 那以下先用一段模拟代码来描写叙述下我出现的问题的: ...

  10. 在Apk应用程序内,查找某个Activity。

    转载请注明出处:http://blog.csdn.net/droyon/article/details/39933677 Intent intent = new Intent(Intent.ACTIO ...