文章 | 入侵攻击 | 安全防御 | 操作系统 | 网站建设 | 网络编程 | 路由交换 | 灾难恢复 | 新闻资讯 | 安全公告
下载 | 漏洞扫描 | 加密破解 | 入侵攻击 | 后门木马 | 溢出程序 | 综合工具 | 安全防护 | 原创发布 | 动画教程
论坛 | 黑客军火 | 配服务器 | 黑客情感 | 免费资源 | 美女贴图 | 灌水无罪 | 在线服务 | 会员照片 | 网站首页
 当前位置:主页 >> 技术文摘 >> 网络编程 >> NET编程 >> 文章内容  
 

 
ASP.NET如何存取SQL Server数据库图片

www.hx99.org 阅读: 时间:2007-07-12 整理:华西黑盟
------------------------------------------------------------------
 SQLServer提供了一个特别的数据类型:image,它是一个包含binary数据的类型。下边这个例子就向你展示了如何将文本或照片放入到数据库中的办法。在这篇文章中我们要看到如何在SQL Server中存储和读取图片。

  1、建立一个表:

  在SQLSERVER中建立这样结构的一个表:


  2、存储图片到SQLSERVER数据库中

  为了能存储到表中,你首先要上传它们到你的WEB服务器上,你可以开发一个webform,它用来将客户端中TextBoxwebcontrol中的图片入到你的WEB服务器上来。将你的 encType属性设置为:myltipart/formdata.

Streamimgdatastream=File1.PostedFile.InputStream;
intimgdatalen=File1.PostedFile.ContentLength;
stringimgtype=File1.PostedFile.ContentType;
stringimgtitle=TextBox1.Text;
byte[]imgdata=newbyte[imgdatalen];
intn=imgdatastream.Read(imgdata,0,imgdatalen);
stringconnstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];

SqlConnectionconnection=newSqlConnection(connstr);

SqlCommandcommand=newSqlCommand
         ("INSERTINTOImageStore(imgtitle,imgtype,imgdata)
         VALUES(@imgtitle,@imgtype,@imgdata)",connection);

SqlParameterparamTitle=newSqlParameter
         ("@imgtitle",SqlDbType.VarChar,50);

paramTitle.Value=imgtitle;
command.Parameters.Add(paramTitle);

SqlParameterparamData=newSqlParameter("@imgdata",SqlDbType.Image );
paramData.Value=imgdata;
command.Parameters.Add(paramData);

SqlParameterparamType=newSqlParameter("@imgtype",SqlDbType.VarChar,50 );
paramType.Value=imgtype;
command.Parameters.Add(paramType);

connection.Open();
intnumRowsAffected=command.ExecuteNonQuery();
connection.Close();
  3、从数据库中恢复读取

  现在让我们来从SQLServer中读取我们放入的数据吧!我们将要输出图片到你的浏览器上,你也可以将它存放到你要的位置。

privatevoidPage_Load(objectsender,System.EventArgse)
{
 stringimgid=Request.QueryString["imgid"];
 stringconnstr=((NameValueCollection)
 Context.GetConfig("appSettings"))["connstr"];
 stringsql="SELECTimgdata,imgtypeFROMImageStoreWHEREid="+imgid;
 SqlConnectionconnection=newSqlConnection(connstr);
 SqlCommandcommand=newSqlCommand(sql,connection);
 connection.Open();
 SqlDataReaderdr=command.ExecuteReader();
 if(dr.Read())
 {
  Response.ContentType=dr["imgtype"].ToString();
  Response.BinaryWrite((byte[])dr["imgdata"]);
 }
 connection.Close();
}
  要注意的是Response.BinaryWrite而不是Response.Write.

  下面给大家一个用于C#Winform的存入、读取程序。其中不同请大家自己比较!(为了方便起见,我将数据库字段简化为二个:imgtitle和imgdata。

usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;
usingSystem.IO;
usingSystem.Data.SqlClient;

namespaceWindowsApplication21
{
 ///<summary>
 ///Form1的摘要说明。
 ///</summary>
 publicclassForm1:System.Windows.Forms.Form
 {
  privateSystem.Windows.Forms.Buttonbutton1;
  ///<summary>
  ///必需的设计器变量。
  ///</summary>
  privateSystem.ComponentModel.Containercomponents=null;
  privatestringConnectionString="IntegratedSecurity=SSPI;Initial Catalog=;Data Source=localhost;";
  privateSqlConnectionconn=null;
  privateSqlCommandcmd=null;
  privateSystem.Windows.Forms.Buttonbutton2;
  privateSystem.Windows.Forms.PictureBoxpic1;
  privateSystem.Windows.Forms.OpenFileDialogopenFileDialog1;
  privatestringsql=null;
  privateSystem.Windows.Forms.Labellabel2;
  privatestringnowId=null;

 publicForm1()
 {
  //
  //Windows窗体设计器支持所必需的
  //
  InitializeComponent();
  conn=newSqlConnection(ConnectionString);

  //
  //TODO:在InitializeComponent调用后添加任何构造函数代码
  //
 }

 ///<summary>
 ///清理所有正在使用的资源。
 ///</summary>
 protectedoverridevoidDispose(booldisposing)
 {
  if(conn.State==ConnectionState.Open)
   conn.Close();
  if(disposing)
  {
   if(components!=null)
   {
    components.Dispose();
   }
  }
  base.Dispose(disposing);

 }

 #regionWindowsFormDesignergeneratedcode
 ///<summary>
 ///设计器支持所需的方法-不要使用代码编辑器修改
 ///此方法的内容。
 ///</summary>
 privatevoidInitializeComponent()
 {
  this.button1=newSystem.Windows.Forms.Button();
  this.pic1=newSystem.Windows.Forms.PictureBox();
  this.button2=newSystem.Windows.Forms.Button();
  this.openFileDialog1=newSystem.Windows.Forms.OpenFileDialog();
  this.label2=newSystem.Windows.Forms.Label();
  this.SuspendLayout();
  //
  //button1
  //
  this.button1.Location=newSystem.Drawing.Point(0,40);
  this.button1.Name="button1";
  this.button1.Size=newSystem.Drawing.Size(264,48);
  this.button1.TabIndex=0;
  this.button1.Text="加入新的图片";
  this.button1.Click+=newSystem.EventHandler(this.button1_Click);
  //
  //pic1
  //
  this.pic1.Location=newSystem.Drawing.Point(280,8);
  this.pic1.Name="pic1";
  this.pic1.Size=newSystem.Drawing.Size(344,264);
  this.pic1.TabIndex=3;
  this.pic1.TabStop=false;
  //
  //button2
  //
  this.button2.Location=newSystem.Drawing.Point(0,104);
  this.button2.Name="button2";
  this.button2.Size=newSystem.Drawing.Size(264,40);
  this.button2.TabIndex=4;
  this.button2.Text="从数据库中恢复图像";
  this.button2.Click+=newSystem.EventHandler(this.button2_Click);
  //
  //openFileDialog1
  //
  this.openFileDialog1.Filter="\"图像文件(*.jpg,*.bmp,*.gif)|*.jpg|*.bmp|*.gif\"";
  //
  //label2
  //
  this.label2.Location=newSystem.Drawing.Point(0,152);
  this.label2.Name="label2";
  this.label2.Size=newSystem.Drawing.Size(264,48);
  this.label2.TabIndex=5;
  //
  //Form1
  //
  this.AutoScaleBaseSize=newSystem.Drawing.Size(6,14);
  this.ClientSize=newSystem.Drawing.Size(632,273);
  this.Controls.AddRange(newSystem.Windows.Forms.Control[]{
    this.label2,
    this.button2,
    this.pic1,
    this.button1});
  this.Name="Form1";
  this.Text="Form1";
  this.Load+=newSystem.EventHandler(this.Form1_Load);
  this.ResumeLayout(false);

 }
 #endregion

 ///<summary>
 ///应用程序的主入口点。
 ///</summary>
 [STAThread]
 staticvoidMain()
 {
  Application.Run(newForm1());
 }

 privatevoidbutton1_Click(objectsender,System.EventArgse)
 {
  openFileDialog1.ShowDialog();

  if(openFileDialog1.FileName.Trim()!="")
  {
   FileInfofi=newFileInfo(openFileDialog1.FileName);

   stringimgtitle=openFileDialog1.FileName;
   intimgdatalen=(int)fi.Length;
   byte[]imgdata=newbyte[imgdatalen];

   Streamimgdatastream=fi.OpenRead();
   intn=imgdatastream.Read(imgdata,0,imgdatalen);


   if(conn.State==ConnectionState.Open)
    conn.Close();
   ConnectionString="IntegratedSecurity=SSPI;"+"InitialCatalog=mydb;"+"Data  Source=localhost;";
   conn.ConnectionString=ConnectionString;


 try
 {
  stringmySelectQuery="INSERTINTOImageStore(imgtitle,imgdata)VALUES (@imgtitle,@imgdata)";
  //stringmySelectQuery="UPDATEImageStoresetimgtitle=@imgtitle,imgdata=@imgdata";
  SqlCommandmyCommand=newSqlCommand(mySelectQuery,conn);

  SqlParameterparamTitle=newSqlParameter("@imgtitle",SqlDbType.VarChar,50 );
  paramTitle.Value=imgtitle;
  myCommand.Parameters.Add(paramTitle);

  SqlParameterparamData=newSqlParameter("@imgdata",SqlDbType.Image );
  paramData.Value=imgdata;
  myCommand.Parameters.Add(paramData);

  conn.Open();
  intnumRowsAffected=myCommand.ExecuteNonQuery();
  conn.Close();
 }
 catch(Exceptionerr)
 {
  MessageBox.Show("您输入名称可能在数据库中已存在或输入为空,请检查!"+err.ToString());
 }
 finally
 {}
}

}

 privatevoidForm1_Load(objectsender,System.EventArgse)
 {
 }

 privatevoidbutton2_Click(objectsender,System.EventArgse)
 {
  //打开数据库连接
  if(conn.State==ConnectionState.Open)
   conn.Close();
  ConnectionString="IntegratedSecurity=SSPI;"+"InitialCatalog=mydb;"+"Data Source=localhost;";
  conn.ConnectionString=ConnectionString;

  //创建数据适配器
  stringsql="SELECT*FROMImageStore";
  SqlCommandcommand=newSqlCommand(sql,conn);

  try
  {conn.Open();}
  catch(Exceptionnewerr)
  {
   MessageBox.Show("不能打开数据联接!");
  }
  finally
  {}

  SqlDataReaderdr=command.ExecuteReader();
  if(dr.Read())
  {
   FileInfofi=newFileInfo("temp");
   FileStreammyStream=fi.Open(FileMode.Create);
   byte[]mydata=((byte[])dr["imgdata"]);
   //label2.Text="您现在看到的是:"+dr["imgtitle"].ToString();
   foreach(byteainmydata)
   {
    myStream.WriteByte(a);
   }
  myStream.Close();
  ImagemyImage=Image.FromFile("temp");
  pic1.Image=myImage;
  pic1.Refresh();
  dr.Close();

 }
 else
 {
  MessageBox.Show("没有成功读入数据!");

 }

 conn.Close();

}

}
}
   -------------------------------------------------------------------------------------------
  上一篇:asp.net中在线用户统计
  下一篇:Asp.net 中在客户端触发服务端事件
   -------------------------------------------------------------------------------------------
用户名:
Email:
评论内容:
 
  精品推荐
推荐:ASPX一句话木马--终
利用ASP.Net 动态生成HTML
asp.net实现验证码
在asp.net中利用session做
Asp.net 中在客户端触发服
Asp.net 中服务端控件事件
ASP.NET上传图片并生成可
ASP.NET AJAX解决网页打开
实现IE浏览器部分菜单命令
Asp.net一夜速成教程
从sqlserver中读取图片
ASP.NET页面间的传值的几
用动态属性和DataView实现
用PagedDataSource类实现D
关于TreeView控件专题
asp.net上传图片并同时生
ASP.NET中水晶报表的使用
ASP.NET 中 Cookie 的基本
ADO.NET使用经验集
Forms身份验证
ASP.NET四种页面导航方式
ASP.NET中如何防范SQL注入
[分享]ASP.NET学习手记```
ASP.NET编程中的十大技巧
用ASP.NET上传图片并生成
关于我们 | 发展历程 | 在线投稿 | 核心监督 | 友情链接 | 网站地图 | 网站留言 | 联系我们
Copyright © 2004-2007 Www.Hx99.Net
版本:华西黑盟网站系统V5.0 Email:root#hx99.org
中国·西安·宝鸡 请使用IE6.0版本, 分辩率1024×768进行浏览
版权所有 任意抄袭 注意完整
陕ICP备06000444号