资源描述
传播优秀Word版文档 ,希望对您有帮助,可双击去除!程序代码:下面的代码实现向SQLServer数据库添加图片和文字的功能。首先,在SQL查询分析器中执行下面的语句,以创建表和存储过程。DropTablePersonGoCreateTablePerson(PersonIDIntIdentity,PersonEmailVarchar(255),PersonNameVarchar(255),PersonSexChar(1),PersonDOBDateTime,PersonImageImage,PersonImageTypeVarchar(255)DropProcsp_person_ispGoCreateProcsp_person_ispPersonEmailVarchar(255),PersonNameVarchar(255),PersonSexChar(1),PersonDOBDateTime,PersonImageImage,PersonImageTypeVarchar(255)AsBeginInsertintoPerson(PersonEmail,PersonName,PersonSex,PersonDOB,PersonImage,PersonImageType)Values(PersonEmail,PersonName,PersonSex,PersonDOB,PersonImage,PersonImageType)EndGo下面就是完整的代码,拷贝即可运行:向SQLServer插入图片PublicSubAddPerson(senderAsObject,eAsEventArgs)DimintImageSizeAsInt64DimstrImageTypeAsStringDimImageStreamAsStream获得图片的大小intImageSize=PersonImage.PostedFile.ContentLength获得图片类型strImageType=PersonImage.PostedFile.ContentType读取图片ImageStream=PersonImage.PostedFile.InputStreamDimImageContent(intImageSize)AsByteDimintStatusAsIntegerintStatus=ImageStream.Read(ImageContent,0,intImageSize)创建Connection和Command对象DimstrCnnAsString=DataSource=.;InitialCatalog=mxh;UserId=sa;Password=;DimmyConnectionAsNewSqlConnection(strCnn)DimmyCommandAsNewSqlCommand(sp_person_isp,myConnection)使用存储过程myCommand.CommandType=CommandType.StoredProcedure向存储过程添加参数DimprmEmailAsNewSqlParameter(PersonEmail,SqlDbType.VarChar,255)prmEmail.Value=txtPersonEmail.TextmyCommand.Parameters.Add(prmEmail)DimprmNameAsNewSqlParameter(PersonName,SqlDbType.VarChar,255)prmName.Value=txtPersonName.TextmyCommand.Parameters.Add(prmName)DimprmSexAsNewSqlParameter(PersonSex,SqlDbType.Char,1)IfsexMale.CheckedThenprmSex.Value=MElseprmSex.Value=FEndIfmyCommand.Parameters.Add(prmSex)DimprmPersonDOBAsNewSqlParameter(PersonDOB,SqlDbType.DateTime)prmPersonDOB.Value=txtPersonDob.TextmyCommand.Parameters.Add(prmPersonDOB)DimprmPersonImageAsNewSqlParameter(PersonImage,SqlDbType.Image)prmPersonImage.Value=ImageContentmyCommand.Parameters.Add(prmPersonImage)DimprmPersonImageTypeAsNewSqlParameter(PersonImageType,SqlDbType.VarChar,255)prmPersonImageType.Value=strImageTypemyCommand.Parameters.Add(prmPersonImageType)TrymyConnection.Open()myCommand.ExecuteNonQuery()myConnection.Close()Response.Write(添加成功!)CatchSQLexcAsSqlExceptionResponse.Write(添加失败,原因:&SQLexc.ToString()EndTryEndSub本日志由 迈克老猫 于 2005-01-06 10:43 PM 编辑引用通告地址 (0):收藏此页迈克老猫 于 2004-06-09 05:16 PM 发表评论:SQLServer提供了一个特别的数据类型:image,它是一个包含.SQLServer提供了一个特别的数据类型:image,它是一个包含binary数据的类型。下边这个例子就向你展示了如何将文本或照片放入到数据库中的办法。在这篇文章中我们要看到如何在SQLServer中存储和读取图片。1、建立一个表:在SQLSERVER中建立这样结构的一个表:列名类型目的IDInteger主键IDIMGTITLEVarchar(50)图片的标题IMGTYPEVarchar(50)图片类型.ASP.NET要以辨认的类型IMGDATAImage用于存储二进制数据2、存储图片到SQLSERVER数据库中为了能存储到表中,你首先要上传它们到你的WEB服务器上,你可以开发一个webform,它用来将客户端中TextBoxwebcontrol中的图片入到你的WEB服务器上来。将你的encType属性设置为:myltipart/formdata.Streamimgdatastream=File1.PostedFile.InputStream;intimgdatalen=File1.PostedFile.ContentLength;stringimgtype=File1.PostedFile.ContentType;stringimgtitle=TextBox1.Text;byteimgdata=newbyteimgdatalen;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.QueryStringimgid;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=drimgtype.ToString();Response.BinaryWrite(byte)drimgdata);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的摘要说明。/summarypublicclassForm1:System.Windows.Forms.FormprivateSystem.Windows.Forms.Buttonbutton1;/summary/必需的设计器变量。/summaryprivateSystem.ComponentModel.Containercomponents=null;privatestringConnectionString=IntegratedSecurity=SSPI;InitialCatalog=;DataSource=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/清理所有正在使用的资源。/summaryprotectedoverridevoidDispose(booldisposing)if(conn.State=ConnectionState.Open)conn.Close();if(disposing)if(components!=null)components.Dispose();base.Dispose(disposing);#regionWindowsFormDesignergeneratedcode/summary/设计器支持所需的方法-不要使用代码编辑器修改/此方法的内容。/summaryprivatevoidInitializeComponent()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.Controlthis.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/应用程序的主入口点。/summarySTAThreadstaticvoidMain()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;byteimgdata=newbyteimgdatalen;Streamimgdatastream=fi.OpenRead();intn=imgdatastream.Read(imgdata,0,imgdatalen);if(conn.State=ConnectionState.Open)conn.Close();ConnectionString=IntegratedSecurity=SSPI;+InitialCatalog=mydb;+DataSource=localhost;conn.ConnectionString=ConnectionString;trystringmySelectQuery=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();finallyprivatevoidForm1_Load(objectsender,System.EventArgse)privatevoidbutton2_Click(objectsender,System.EventArgse)/打开数据库连接if(conn.State=ConnectionState.Open)conn.Close();ConnectionString=IntegratedSecurity=SSPI;+InitialCatalog=mydb;+DataSource=localhost;conn.ConnectionString=ConnectionString;/创建数据适配器stringsql=SELECT*FROMImageStore;SqlCommandcommand=newSqlCommand(sql,conn);tryconn.Open();catch(Exceptionnewerr)MessageBox.Show(不能打开数据联接!);finallySqlDataReaderdr=command.ExecuteReader();if(dr.Read()FileInfofi=newFileInfo(temp);FileStreammyStream=fi.Open(FileMode.Create);bytemydata=(byte)drimgdata);/label2.Text=您现在看到的是:+drimgtitle.ToString();foreach(byteainmydata)myStream.WriteByte(a);myStream.Close();ImagemyImage=Image.FromFile(temp);pic1.Image=myImage;pic1.Refresh();dr.Close();elseMessageBox.Show(没有成功读入数据!);conn.Close();KusTa 于 2004-06-09 02:51 AM 发表评论:用VB6读写数据库中的图片(可能扯得有点远,不需要可以不看)http:.用VB6读写数据库中的图片(可能扯得有点远,不需要可以不看)-1,以人名和相关图片为例说明,数据库为Access,有如下字段:Namechar,pictureOLEobject,FileLengthNumber。当为mssql时,将picture改为lob即可。2,示例包含control:commomdialog,picture,listbox。源码如下:引用内容:OptionExplicitPrivateDeclareFunctionGetTempFileNameLibkernel32AliasGetTempFileNameA(ByVallpszPathAsString,ByVallpPrefixStringAsString,ByValwUniqueAsLong,ByVallpTempFileNameAsString)AsLongPrivateDeclareFunctionGetTempPathLibkernel32AliasGetTempPathA(ByValnBufferLengthAsLong,ByVallpBufferAsString)AsLongPrivateConstMAX_PATH=260Privatem_DBConnAsADODB.ConnectionPrivateConstBLOCK_SIZE=10000注释:Returnatemporaryfilename.PrivateFunctionTemporaryFileName()AsStringDimtemp_pathAsStringDimtemp_fileAsStringDimlengthAsLong注释:Getthetemporaryfilepath.temp_path=Space$(MAX_PATH)length=GetTempPath(MAX_PATH,temp_path)temp_path=Left$(temp_path,length)注释:Getthefilename.temp_file=Space$(MAX_PATH)GetTempFileNametemp_path,per,0,temp_fileTemporaryFileName=Left$(temp_file,InStr(temp_file,Chr$(0)-1)EndFunctionPrivateSubForm_Load()Dimdb_fileAsStringDimrsAsADODB.Recordset注释:Getthedatabasefilename.db_file=App.PathIfRight$(db_file,1)Thendb_file=db_file&db_file=db_file&dbpict.mdb注释:Openthedatabaseconnection.Setm_DBConn=NewADODB.Connectionm_DBConn.Open_Provider=Microsoft.Jet.OLEDB.4.0;&_DataSource=&db_file&;&_PersistSecurityInfo=False注释:Getthelistofpeople.Setrs=m_DBConn.Execute(SELECTNameFROMPeopleORDERBYName,adCmdText)DoWhileNotrs.EOFlstPeople.AddItemrs!Namers.MoveNextLooprs.CloseSetrs=NothingEndSubPrivateSubForm_Resize()lstPeople.Height=ScaleHeightEndSub注释:Displaytheclickedperson.PrivateSublstPeople_Click()DimrsAsADODB.RecordsetDimbytes()AsByteDimfile_nameAsStringDimfile_numAsIntegerDimfile_lengthAsLongDimnum_blocksAsLongDimleft_overAsLongDimblock_numAsLongDimhgtAsSinglepicPerson.Visible=FalseScreen.MousePointer=vbHourglassDoEvents注释:Gettherecord.Setrs=m_DBConn.Execute(SELECT*FROMPeopleWHEREName=注释:&_lstPeople.Text&注释:,adCmdText)Ifrs.EOFThenExitSub注释:Getatemporaryfilename.file_name=TemporaryFileName()注释:Openthefile.file_num=FreeFileOpenfile_nameForBinaryAs#file_num注释:Copythedataintothefile.file_length=rs!FileLengthnum_blocks=file_length/BLOCK_SIZEleft_over=file_lengthModBLOCK_SIZEForblock_num=1Tonum_blocksbytes()=rs!Picture.GetChunk(BLOCK_SIZE)Put#file_num,bytes()Nextblock_numIfleft_over0Thenbytes()=rs!Picture.GetChunk(left_over)Put#file_num,bytes()EndIfClose#file_num注释:Displaythepicturefile.picPerson.Picture=LoadPicture(file_name)picPerson.Visible=TrueWidth=picPerson.Left+picPerson.Width+Width-ScaleWidthhgt=picPerson.Top+picPerson.Height+Height-ScaleHeightIfhgt1440Thenhgt=1440Height=hgtKillfile_nameScreen.MousePointer=vbDefaultEndSubPrivateSubmnuRecordAdd_Click()DimrsAsADODB.RecordsetDimperson_nameAsStringDimfile_numAsStringDimfile_lengthAsStringDimbytes()AsByteDimnum_blocksAsLongDimleft_overAsLongDimblock_numAsLongperson_name=InputBox(Name)IfLen(person_name)=0ThenExitSubdlgPicture.Flags=_cdlOFNFileMustExistOr_cdlOFNHideReadOnlyOr_cdlOFNExplorerdlgPicture.CancelError=TruedlgPicture.Filter=GraphicsFiles|*.bmp;*.ico;*.jpg;*.gifOnErrorResumeNextdlgPicture.ShowOpenIfErr.Number=cdlCancelThenExitSubElseIfErr.Number0ThenMsgBoxError&Format$(Err.Number)&_selectingfile.&vbCrLf&Err.DescriptionExitSubEndIf注释:Openthepicturefile.file_num=FreeFileOpendlgPicture.FileNameForBinaryAccessReadAs#file_numfile_length=LOF(file_num)Iffile_length0Thennum_blocks=file_length/BLOCK_SIZEleft_over=file_lengthModBLOCK_SIZESetrs=NewADODB.Recordsetrs.CursorType=adOpenKeysetrs.LockType=adLockOptimisticrs.OpenSelectName,Picture,FileLengthFROMPeople,m_DBConnrs.AddNewrs!Name=person_namers!FileLength=file_lengthReDimbytes(BLOCK_SIZE)Forblock_num=1Tonum_blocksGet#file_num,bytes()rs!Picture.AppendChunkbytes()Nextblock_numIfleft_over0ThenReDimbytes(left_over)Get#file_num,bytes()rs!Picture.AppendChunkbytes()EndIfrs.UpdateClose#file_numlstPeople.AddItemperson_namelstPeople.Text=person_nameEndIfEndSubb广告时间:/b迈克老猫 于 2004-06-08 10:22 PM 发表评论:codeUploadFile.aspx:%PageLanguage=V.程序代码:UploadFile.aspx:SubImageStored(senderAsObject,EAsEventArgs)dimimgdatastreamasStream=File1.PostedFile.Input
展开阅读全文