sql server提供了一个特别的数据类型:image,它是一个包含binary数据的类型。下边这个例子就向你展示了如何将文本或照片放入到数据库中的办法。在这篇文章中我们要看到如何在sql server中存储和读取图片。
1、建立一个表:
在sql server中建立这样结构的一个表:
| 列名 | 类型 | 目的 |
| id | integer | 主键id |
| imgtitle | varchar(50) | 图片的标题 |
| imgtype | varchar(50) | 图片类型. asp.net要以辨认的类型 |
| imgdata | image | 用于存储二进制数据 |
| stream imgdatastream = file1.postedfile.inputstream; int imgdatalen = file1.postedfile.contentlength; string imgtype = file1.postedfile.contenttype; string imgtitle = textbox1.text; byte[] imgdata = new byte[imgdatalen]; int n = imgdatastream.read(imgdata,0,imgdatalen); string connstr=((namevaluecollection)context.getconfig("appsettings"))["connstr"]; sqlconnection connection = new sqlconnection(connstr); sqlcommand command = new sqlcommand ("insert into imagestore(imgtitle,imgtype,imgdata) values ( @imgtitle, @imgtype,@imgdata )", connection ); sqlparameter paramtitle = new sqlparameter ("@imgtitle", sqldbtype.varchar,50 ); paramtitle.value = imgtitle; command.parameters.add( paramtitle); sqlparameter paramdata = new sqlparameter( "@imgdata", sqldbtype.image ); paramdata.value = imgdata; command.parameters.add( paramdata ); sqlparameter paramtype = new sqlparameter( "@imgtype", sqldbtype.varchar,50 ); paramtype.value = imgtype; command.parameters.add( paramtype ); connection.open(); int numrowsaffected = command.executenonquery(); connection.close(); |
| private void page_load(object sender, system.eventargs e) { string imgid =request.querystring["imgid"]; string connstr=((namevaluecollection) context.getconfig("appsettings"))["connstr"]; string sql="select imgdata, imgtype from imagestore where id = " + imgid; sqlconnection connection = new sqlconnection(connstr); sqlcommand command = new sqlcommand(sql, connection); connection.open(); sqldatareader dr = command.executereader(); if(dr.read()) { response.contenttype = dr["imgtype"].tostring(); response.binarywrite( (byte[]) dr["imgdata"] ); } connection.close(); } |
| using system; using system.drawing; using system.collections; using system.componentmodel; using system.windows.forms; using system.data; using system.io; using system.data.sqlclient; namespace windowsapplication21 { /// <summary> /// form1 的摘要说明。 /// </summary> public class form1 : system.windows.forms.form { private system.windows.forms.button button1; /// <summary> /// 必需的设计器变量。 /// </summary> private system.componentmodel.container components = null; private string connectionstring = "integrated security=sspi;initial catalog=;data source=localhost;"; private sqlconnection conn = null; private sqlcommand cmd = null; private system.windows.forms.button button2; private system.windows.forms.picturebox pic1; private system.windows.forms.openfiledialog openfiledialog1; private string sql = null; private system.windows.forms.label label2; private string nowid=null; public form1() { // // windows 窗体设计器支持所必需的 // initializecomponent(); conn = new sqlconnection(connectionstring); // // todo: 在 initializecomponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void dispose( bool disposing ) { if (conn.state == connectionstate.open) conn.close(); if( disposing ) { if (components != null) { components.dispose(); } } base.dispose( disposing ); } #region windows form designer generated code /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void initializecomponent() { this.button1 = new system.windows.forms.button(); this.pic1 = new system.windows.forms.picturebox(); this.button2 = new system.windows.forms.button(); this.openfiledialog1 = new system.windows.forms.openfiledialog(); this.label2 = new system.windows.forms.label(); this.suspendlayout(); // // button1 // this.button1.location = new system.drawing.point(0, 40); this.button1.name = "button1"; this.button1.size = new system.drawing.size(264, 48); this.button1.tabindex = 0; this.button1.text = "加入新的图片"; this.button1.click += new system.eventhandler(this.button1_click); // // pic1 // this.pic1.location = new system.drawing.point(280, 8); this.pic1.name = "pic1"; this.pic1.size = new system.drawing.size(344, 264); this.pic1.tabindex = 3; this.pic1.tabstop = false; // // button2 // this.button2.location = new system.drawing.point(0, 104); this.button2.name = "button2"; this.button2.size = new system.drawing.size(264, 40); this.button2.tabindex = 4; this.button2.text = "从数据库中恢复图像"; this.button2.click += new system.eventhandler(this.button2_click); // // openfiledialog1 // this.openfiledialog1.filter = "\"图像文件(*.jpg,*.bmp,*.gif)*.jpg*.bmp*.gif\""; // // label2 // this.label2.location = new system.drawing.point(0, 152); this.label2.name = "label2"; this.label2.size = new system.drawing.size(264, 48); this.label2.tabindex = 5; // // form1 // this.autoscalebasesize = new system.drawing.size(6, 14); this.clientsize = new system.drawing.size(632, 273); this.controls.addrange(new system.windows.forms.control[] { this.label2, this.button2, this.pic1, this.button1}); this.name = "form1"; this.text = "form1"; this.load += new system.eventhandler(this.form1_load); this.resumelayout(false); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [stathread] static void main() { application.run(new form1()); } private void button1_click(object sender, system.eventargs e) { openfiledialog1.showdialog (); if (openfiledialog1.filename.trim()!="") { fileinfo fi = new fileinfo(openfiledialog1.filename); string imgtitle=openfiledialog1.filename; int imgdatalen=(int)fi.length; byte[] imgdata = new byte[imgdatalen]; stream imgdatastream=fi.openread(); int n=imgdatastream.read(imgdata,0,imgdatalen); if( conn.state == connectionstate.open) conn.close(); connectionstring ="integrated security=sspi;" + "initial catalog=mydb;" +"data source=localhost;"; conn.connectionstring = connectionstring; try { string myselectquery = "insert into imagestore(imgtitle,imgdata) values (@imgtitle, @imgdata )"; //string myselectquery="update imagestore set imgtitle=@imgtitle,imgdata=@imgdata" ; sqlcommand mycommand = new sqlcommand(myselectquery, conn); sqlparameter paramtitle = new sqlparameter("@imgtitle", sqldbtype.varchar,50 ); paramtitle.value = imgtitle; mycommand.parameters.add( paramtitle); sqlparameter paramdata = new sqlparameter( "@imgdata", sqldbtype.image ); paramdata.value = imgdata; mycommand.parameters.add( paramdata ); conn.open(); int numrowsaffected = mycommand.executenonquery(); conn.close(); } catch(exception err) { messagebox.show("您输入名称可能在数据库中已存在或输入为空,请检查!"+err.tostring() ); } finally {} } } private void form1_load(object sender, system.eventargs e) { } private void button2_click(object sender, system.eventargs e) { //打开数据库连接 if( conn.state == connectionstate.open) conn.close(); connectionstring ="integrated security=sspi;" + "initial catalog=mydb;" +"data source=localhost;"; conn.connectionstring = connectionstring; // 创建数据适配器 string sql="select * from imagestore" ; sqlcommand command = new sqlcommand(sql, conn); try {conn.open();} catch(exception newerr) { messagebox.show(" 不能打开数据联接!") ; } finally {} sqldatareader dr = command.executereader(); if(dr.read()) { fileinfo fi = new fileinfo("temp"); filestream mystream=fi.open(filemode.create); byte[] mydata=((byte[])dr["imgdata"]); //label2.text="您现在看到的是:"+ dr["imgtitle"].tostring(); foreach(byte a in mydata) { mystream.writebyte(a); } mystream.close(); image myimage=image.fromfile("temp") ; pic1.image=myimage; pic1.refresh(); dr.close (); } else { messagebox.show("没有成功读入数据!") ; } conn.close(); } } } |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器