Storing and Retrieving Images from SQL Server using Microsoft .NET
原文 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
- 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]
- Actually
IMAGE
field is just holding the reference to the page containing the binary data so we have to convert our image into bytes.- I used a file open dialog box to locate the file.
Collapse | Copy Code
this.openFileDialog1.ShowDialog(this);
string strFn=this.openFileDialog1.FileName; - By using
FileInfo
class, I retrieved the file size:Collapse | Copy Code
FileInfo fiImage=new FileInfo(strFn);
- Declare an array of that size.
Collapse | Copy Code
this.m_lImageFileLength=fiImage.Length;
m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)]; - 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);
}
} - I used a file open dialog box to locate the file.
- Saving byte array data to database.
- Create command text to insert record.
Collapse | Copy Code
this.sqlCommand1.CommandText=
"INSERT INTO tblImgData(ID,Name,Picture)" +
" values(@ID,@Name,@Picture)"; - 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 ofIMAGE
type Field. - 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. - 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();
}
} - Create command text to insert record.
Retrieving Image
Retrieving images from the database is the exact reverse process of saving images to the database.
- First create command text to retrieve record.
Collapse | Copy Code
SqlCommand cmdSelect = new SqlCommand("select Picture" +
" from tblImgData where ID=@ID",
this.sqlConnection1); - Create parameter for the query.
Collapse | Copy Code
cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
- Provide value to the parameter.
Collapse | Copy Code
cmdSelect.Parameters["@ID"].Value=this.editID.Text;
- 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 tobyte
array. - 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(); - And display the image anywhere you want to display.
Collapse | Copy Code
pictureBox1.Image=Image.FromFile(strfn);
Complete Image Retrieving 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的更多相关文章
- 转载: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 ...
- SQL SERVER 2012/2014 链接到 SQL SERVER 2000的各种坑
本文总结一下SQL SERVER 2012/2014链接到SQL SERVER 2000的各种坑,都是在实际应用中遇到的疑难杂症.可能会有人说怎么还在用SQL SERVER 2000,为什么不升级呢? ...
- 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) ) 案例介绍: 对一个数据 ...
- [转]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/ ...
- sql server数据库连接问题处理
下面请一字一句地看,一遍就设置成功,比你设置几十遍失败,费时会少得多. 首先,在连接数据库之前必须保证SQL Server 2012是采用SQL Server身份验证方式而不是windows身份验证方 ...
- Sql Server 2008卸载后再次安装一直报错
sql server 2008卸载之后再次安装一直报错问题. 第一:由于上一次的卸载不干净,可参照百度完全卸载sql server2008 的方式 1. 用WindowsInstaller删除所有与S ...
- [转载]在SQL Server 中,如何实现DBF文件和SQL Server表之间的导入或者导出?
原来使用SQL Server 2000数据库,通过DTS工具很方便地在SQL Server和DBF文件之间进行数据的导入和导出,现在安装了SQL Server2005之后,发现其提供的“SQL Ser ...
- sql server 基础教程[温故而知新三]
子曰:“温故而知新,可以为师矣.”孔子说:“温习旧知识从而得知新的理解与体会,凭借这一点就可以成为老师了.“ 尤其是咱们搞程序的人,不管是不是全栈工程师,都是集十八般武艺于一身.不过有时候有些知识如果 ...
- 招聘 微软全球技术支持中心 sql server组
微软亚太区全球技术支持中心(APGC CSS)是微软为个人用户.开发者.IT 专业人员到合作伙伴和企业级合作伙伴提供全方位.多元化的服务和技术支持的部门.一个优秀的SQL Server技术支持工程师应 ...
随机推荐
- 冒泡排序算法 C++和PHP达到
冒泡排序是小元素向前或向后的大要素.两个相邻元件之间的比较结果更.交换也这两个元件之间发生.它是最慢的排序算法. 效率最低的算法. 时间复杂度: 它是最差时间复杂度为:O(n^2),冒泡排序最好的时间 ...
- 【Android进阶】Android面试题目整理与讲解(一)
这一篇文章专门整理一下研究过的Android面试题,内容会随着学习不断的增加,如果答案有错误,希望大家可以指正 1.简述Activity的生命周期 当Activity开始启动的时候,首先调用onCre ...
- Quartz CronTrigger应用
CronTrigger配置格式: 格式: [第二] [支] [小时] [日本] [月] [周] [年] 序号 说明 是否必填 同意填写的值 同意的通配符 1 秒 是 0-59 , ...
- Cordova探险系列(三)
自从3.0之后.Cordova默认是关闭全部关于设备原生特性功能的,所以我们要通过加入插件来启动原生特性. 这里以Accelerometer(加速度感应器)为例,来学习怎样使用设备原生特性. 1.加入 ...
- MVC Razor标签
1. RenderBody在Razor引擎中没有了“母版页”,取而代之的是叫做“布局”的页面(_Layout.cshtml)放在了共享视图文件夹中.在这个页面中,会看到标签里有这样一条语句:@Rend ...
- Java OCR tesseract 图像智能字符识别技术
公司有需求啊,所以就得研究哈,最近公司需要读验证码,于是就研究起了图像识别,应该就是传说中的(OCR:光学字符识别OCR),下面把今天的收获整理一个给大家做个分享. 本人程序用的tesseract,官 ...
- FTP文件操作之上传文件
上传文件是一个比较常用的功能,前段时间就做了一个上传图片的模块.开始采用的是共享文件夹的方式,后来发现这种方法不太好.于是果断将其毙掉,后来选择采用FTP的方式进行上传.个人感觉FTP的方式还是比较好 ...
- Mybatis简单的入门之增删改查
一般的过程例如以下 1.加入Mybatis所须要的包,和连接数据库所需的包 2.配置mybatis-config.xml文件 3.配置与pojo相应的映射文件 mybatis-config,xml & ...
- Android 浏览器开发WebView setBlockNetworkImage本末
含义本身防止网络数据图片 webSettings.setBlockNetworkImage(true); 停止发布数据 webSettings.setBlockNetworkImage(false); ...
- [LeetCode299]Bulls and Cows
题目: You are playing the following Bulls and Cows game with your friend: You write down a number and ...