存储过程_将图片存入数据库

合集下载

如何将图片插入到数据库中

如何将图片插入到数据库中

试验十数据库编程‎1、新建项目项目名称为‎“d bgl”。

2、设计如下窗‎体:窗体上放置‎的控件有:7个按钮,一个gro‎upBox‎,4个lab‎el,4个tex‎tBox,1个pic‎tureB‎o x和1个‎d ataG‎r idVi‎e w。

3、编写连接数‎据库的类鼠标单击菜‎单栏上的“项目”选择“项目”菜单中的“添加类”命令,为“dbgl”项目添加连‎接数据库的‎类,类名是:DbCon‎n ecti‎o n。

如下图所示‎:DbCon‎n ecti‎o n类的代‎码如下图所‎示:注意需要引‎入Sy st‎e m.Data.SqlCl‎i ent名‎称空间。

4、编写操作数‎据的类为“dbgl”项目添加操‎作数据的类‎,该类名为“DbOpe‎r atio‎n”。

首先,实例化“DbCon‎n ecti‎o n”类,代码如下:其次,编写方法g‎e tdat‎a set,该方法返回‎一个Dat‎aSet对‎象的数据集‎。

代码如下:接着编写执‎行SQL语‎句的方法“sqlcm‎d”。

该方法的代‎码如下:最后编写方‎法“GetTa‎b le”,该方法用于‎返回一个D‎a taTa‎b le类型‎的数据。

代码如下:5、为窗体编写‎代码,完成对数据‎库操作的功‎能。

在窗体的代‎码视图中:(1)定义一个窗‎体级别的B‎i ndin‎g Mana‎g erBa‎s e类变量‎m ybin‎d用来管理‎多个控件绑‎定到一个数‎据源,以便实现同‎步操作。

代码如下:(2)在窗体的L‎o ad事件‎中编写,为相关控件‎绑定相数据‎。

代码如下:(3)为“第一条”按钮控件编‎写代码:代码如下图‎所示:(4)为“下一条”按钮控件编‎写代码:代码如下图‎所示:(5)为“上一条”按钮控件编‎写代码:代码如下图‎所示:(6)为“最后一条”按钮控件编‎写代码:代码(略)。

自己编写(7)给“新增”按钮编写代‎码,完成添加一‎条记录首先,给项目添加‎一个窗体,窗体名称为‎“FormB‎a se”。

net 图片的二进制数据库存储和显示

net 图片的二进制数据库存储和显示

.net 图片的二进制数据库存储和显示2009-05-26 10:55:53| 分类:net技术| 标签:|字号大中小订阅与图片的二进制数据库存储和显示1.将图片以二进制存入数据库2.读取二进制图片在页面显示3.设置Image控件显示从数据库中读出的二进制图片4.GridView中ImageField以URL方式显示图片5.GridView显示读出的二进制图片====================用到的知识点:FileSteam fs=new FileSteam(fileName,FileMode.Open,FileAccess.Read);BinaryReader binaryReader=new BinaryReader(fs);byte[] myByte=new byte[fs.length];binaryReader.Read(myByte,0,Convet.ToInt32(fs.Length));fs.close()FileInfo fl=new FileInfo(fileName);string imgName=;Memorystream ms=new MemoryStream();byte[] imgByte=(byte[])rd.GetValue(0);Stream imgStream=new MemoryStream(imgByte);pb.Image=Image.FromStream(imgStream);DataView dv=(DataView)cmb.SelectedItem;string imgId=dv.Row["id"].ToString();============================1.将图片以二进制存入数据库C#--------------------------//保存图片到数据库protected void Button1_Click(object sender, EventArgs e){//图片路径string strPath = "~/photo/03.JPG";string strPhotoPath = Server.MapPath(strPath);//读取图片FileStream fs = new System.IO.FileStream(strPhotoPath, FileMode.Open, FileAccess.Read);BinaryReader br = new BinaryReader(fs);byte[] photo = br.ReadBytes((int)fs.Length);br.Close();fs.Close();//存入SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");string strComm = " INSERT INTO personPhoto(personName, personPhotoPath, personPhoto) ";strComm += " VALUES('wangwu', '" + strPath + "', @photoBinary )";SqlCommand myComm = new SqlCommand(strComm, myConn);myComm.Parameters.Add("@photoBinary", SqlDbType.Binary,photo.Length);myComm.Parameters["@photoBinary"].Value = photo;myConn.Open();myComm.ExecuteNonQuery();myConn.Close();}'保存图片到数据库Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)'图片路径Dim strPath As String = "~/photo/03.JPG"Dim strPhotoPath As String = Server.MapPath(strPath)'读取图片Dim fs As FileStream = New System.IO.FileStream(strPhotoPath, FileMode.Open, FileAccess.Read)Dim br As BinaryReader = New BinaryReader(fs)Dim photo() As Byte = br.ReadBytes(CType(fs.Length,Integer))br.Closefs.Close'存入Dim myConn As SqlConnection = New SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa")Dim strComm As String = " INSERT INTO personPhoto(personName, personPhotoPath, personPhoto) "strComm = (strComm + (" VALUES('wangwu', '" _+ (strPath + "', @photoBinary )")))Dim myComm As SqlCommand = New SqlCommand(strComm, myConn)myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length)myComm.Parameters("@photoBinary").Value = photomyConn.OpenmyComm.ExecuteNonQuerymyConn.CloseEnd Sub2.读取二进制图片在页面显示C#--------------------------//读取图片SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");string strComm = " SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ";SqlCommand myComm = new SqlCommand(strComm, myConn);myConn.Open();SqlDataReader dr = myComm.ExecuteReader();while (dr.Read()){byte[] photo = (byte[])dr["personPhoto"];this.Response.BinaryWrite(photo);}dr.Close();myConn.Close();或SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ", myConn);DataSet myds = new DataSet();myConn.Open();myda.Fill(myds);myConn.Close();//byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];this.Response.BinaryWrite(photo);Dim myConn As SqlConnection = New SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa")Dim strComm As String = " SELECT personPhoto FROM personPhoto WHERE personName='wangwu' "Dim myComm As SqlCommand = New SqlCommand(strComm, myConn)myConn.OpenDim dr As SqlDataReader = myComm.ExecuteReaderWhile dr.ReadDim photo() As Byte = CType(dr("personPhoto"),Byte())Me.Response.BinaryWrite(photo)End Whiledr.ClosemyConn.Close或Dim myConn As SqlConnection = New SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa")Dim myda As SqlDataAdapter = New SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ", myConn)Dim myds As DataSet = New DataSetmyConn.Openmyda.Fill(myds)myConn.CloseDim photo() As Byte = CType(myds.Tables(0).Rows(0)("personPhoto"),Byte())Me.Response.BinaryWrite(photo)3.设置Image控件显示从数据库中读出的二进制图片C#---------------------------------------------SqlConnection myConn = new SqlConnection("Data Source=192.168.0.36;Initial Catalog=TestDB;User ID=sa;Password=sa");SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ", myConn);DataSet myds = new DataSet();myConn.Open();myda.Fill(myds);myConn.Close();//byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];//图片路径string strPath = "~/photo/wangwu.JPG";string strPhotoPath = Server.MapPath(strPath);//保存图片文件BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate));bw.Write(photo);bw.Close();//显示图片this.Image1.ImageUrl = strPath;Dim myConn As SqlConnection = New SqlConnection("Data Source=192.168.0.36;Initial Catalog=TestDB;User ID=sa;Password=sa")Dim myda As SqlDataAdapter = New SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ", myConn)Dim myds As DataSet = New DataSetmyConn.Openmyda.Fill(myds)myConn.CloseDim photo() As Byte = CType(myds.Tables(0).Rows(0)("personPhoto"),Byte())Dim strPath As String = "~/photo/wangwu.JPG"Dim strPhotoPath As String = Server.MapPath(strPath)Dim bw As BinaryWriter = New BinaryWriter(File.Open(strPhotoPath, FileMode.OpenOrCreate))bw.Write(photo)bw.Close'显示图片Me.Image1.ImageUrl = strPath4.GridView中ImageField以URL方式显示图片----------------------------<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"><Columns><asp:BoundField DataField="personName" HeaderText="姓名" /><asp:ImageField DataImageUrlField="personPhotoPath"HeaderText="图片"></asp:ImageField></Columns></asp:GridView>后台直接绑定即可5.GridView显示读出的二进制图片------------------------------//样板列<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound"><Columns><asp:BoundField DataField="personName" HeaderText="姓名" /><asp:ImageField DataImageUrlField="personPhotoPath"HeaderText="图片"></asp:ImageField><asp:TemplateField HeaderText="图片"><ItemTemplate><asp:Image ID="Image1" runat="server" /></ItemTemplate></asp:TemplateField></Columns></asp:GridView>//绑定C#protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){if (e.Row.RowIndex < 0)return;// ponentModel.Containerstring strPersonName = (string)DataBinder.Eval(e.Row.DataItem, "personName");Image tmp_Image = (Image)e.Row.Cells[2].FindControl("Image1");if (!System.Convert.IsDBNull(DataBinder.Eval(e.Row.DataItem, "personPhoto"))){//byte[] photo = (byte[])DataBinder.Eval(e.Row.DataItem, "personPhoto");//图片路径string strPath = "~/photo/" + strPersonName.Trim() + ".JPG";string strPhotoPath = Server.MapPath(strPath);//保存图片文件BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath, FileMode.OpenOrCreate));bw.Write(photo);bw.Close();//显示图片tmp_Image.ImageUrl = strPath;}}Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)If (e.Row.RowIndex < 0) ThenReturnEnd If' ponentModel.ContainerDim strPersonName As String = CType(DataBinder.Eval(e.Row.DataItem, "personName"),String)Dim tmp_Image As Image = CType(e.Row.Cells(2).FindControl("Image1"),Image)If Not System.Convert.IsDBNull(DataBinder.Eval(e.Row.DataItem, "personPhoto")) Then'Dim photo() As Byte = CType(DataBinder.Eval(e.Row.DataItem, "personPhoto"),Byte())'GDim strPath As String = ("~/photo/" _+ (strPersonName.Trim + ".JPG"))Dim strPhotoPath As String = Server.MapPath(strPath)'XGDim bw As BinaryWriter = New BinaryWriter(File.Open(strPhotoPath, FileMode.OpenOrCreate))bw.Write(photo)bw.Close'>:Gtmp_Image.ImageUrl = strPathEnd IfEnd SubSQL 2005中存储图片2010-12-22 21:46:51| 分类:SQL server | 标签:scmd 图片 fs int conn |字号大中小订阅转成二进制C# 代码一、将图片写入数据库中的方法:SqlConnection conn=new SqlConnection("server=.;database=pubs;trusted_connection=Yes");conn.Open();SqlCommand scmd = null;string Path = Application.StartupPath + "//Imgren"; //为获取文件的根目录int j = 0;FileStream fs=null;for (int i = 1; i <= 13; i++) //利用循环添加一次添加图片{string sql = "insert into tb_Image values(@a,@b)"; //利用参数实现图片添加scmd = new SqlCommand(sql, scon);scmd.Parameters.Add("@a", SqlDbType.Int);scmd.Parameters["@a"].Value = i; //记住该方法,将值存入参数内byte[] bt = new byte[10240]; //初始化图片大小//创建图片写入流fs = new FileStream(Path + "//" + i + ".bmp", FileMode.OpenOrCreate, FileAccess.Read);fs.Read(bt, 0, bt.Length); //读取图片的字节数scmd.Parameters.Add("@b", SqlDbType.Image, (int)fs.Length);scmd.Parameters["@b"].Value = bt; //将图片的字节数存入参数内j = scmd.ExecuteNonQuery();}if (j > 0)MessageBox.Show("将图片写入数据库成功!!!", "友好提示");elseMessageBox.Show("将图片写入数据库失败!!!", "友好提示");fs.Close(); //关闭释放流资源二、从数据库中读取图片到picturebox中根据编号显示图片哦:SqlConnection conn=new SqlConnection("server=.;database=pubs;trusted_connection=Yes");conn.Open();SqlCommand scmd = null;string sql = "select I_image from tb_image where I_id=" +int.Parse(textBox1.Text.Trim()) + "";scmd = new SqlCommand(sql, scon);SqlDataReader red = scmd.ExecuteReader();if (red.Read()){//创建支持存储区的内存流MemoryStream ms = new MemoryStream((byte[])red[0]);Image img = Image.FromStream(ms, true); //该方法: FromStream()为验证图像的流this.pictureBox1.Image = img;}red.Close(); //关闭资源。

图片保存到mysql数据库

图片保存到mysql数据库

在我们设计和制作网站的过程中,有时把图片保存到数据库中要比存成文件的形式更加方便。

PHP和MySQL这对黄金组合可以很容易的实现上述功能。

在本文中,我们将会向读者介绍如何把图片保存到MySQL数据库中以及如何将数据库中的图片显示出来。

设置数据库我们通常在数据库中所使用的文本或整数类型的字段和需要用来保存图片的字段的不同之处就在于两者所需要保存的数据量不同。

MySQL数据库使用专门的字段来保存大容量的数据,数据类型为BLOB。

MySQL数据库为BLOB做出的定义如下:BLOB数据类型是一种大型的二进制对象,可以保存可变数量的数据。

BLOB具有四种类型,分别是TINYBLOB,BLOB, MEDIUMBLOB 和LONGBLOB,区别在于各自所能够保存的最大数据长度不同。

在介绍了所需要使用的数据类型之后,我们可以使用以下语句创建保存图象的数据表。

CREATE TABLE Images ( PicNum int NOT NULL AUTO_INCREMENT PRIMARY KEY, Image BLOB );编写上传脚本关于如何实现文件的上传,我们在这里就不再介绍了。

现在,我们主要来看一下如何接收上传文件并将其存入到MySQL数据库中。

具体的脚本代码如下,其中我们假定文件上传域的名称为Picture。

<? If($Picture != "none") { $PSize = filesize($Picture); $mysqlPicture = addslashes(fread (fopen($Picture, "r"), $PSize)); mysql_connect($host,$username,$password) or die("Unable to connect to SQL server"); @mysql_select_db($db) or die("Unable to select database"); mysql_query("INSERT INTO Images (Image) VALUES '($mysqlPicture')") or die("Can't Perform Query"); } else { echo"You did not upload any picture"; } ?>这样,我们就可以成功的把图片保存到数据库中。

将图片储存在MySQL数据库中的几种方法

将图片储存在MySQL数据库中的几种方法

将图⽚储存在MySQL数据库中的⼏种⽅法通常对⽤户上传的图⽚需要保存到数据库中。

解决⽅法⼀般有两种:1、将图⽚保存的路径存储到数据库;2、将图⽚以⼆进制数据流的形式直接写⼊数据库字段中。

以下为具体⽅法:⼀、保存图⽚的上传路径到数据库: string uppath="";//⽤于保存图⽚上传路径 //获取上传图⽚的⽂件名 string fileFullname = this.FileUpload1.FileName; //获取图⽚上传的时间,以时间作为图⽚的名字可以防⽌图⽚重名 string dataName = DateTime.Now.ToString("yyyyMMddhhmmss"); //获取图⽚的⽂件名(不含扩展名) string fileName = fileFullname.Substring(stIndexOf("\\") + 1); //获取图⽚扩展名 string type = fileFullname.Substring(stIndexOf(".") + 1); //判断是否为要求的格式 if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF") { //将图⽚上传到指定路径的⽂件夹 this.FileUpload1.SaveAs(Server.MapPath("~/upload") + "\\" + dataName + "." + type); //将路径保存到变量,将该变量的值保存到数据库相应字段即可 uppath = "~/upload/" + dataName + "." + type; }⼆、将图⽚以⼆进制数据流直接保存到数据库:引⽤如下命名空间:using System.Drawing; using System.IO; using System.Data.SqlClient; 设计数据库时,表中相应的字段类型为iamge 保存: //图⽚路径 string strPath = this.FileUpload1.PostedFile.FileName.ToString (); //读取图⽚ FileStream fs = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); byte[] photo = br.ReadBytes((int)fs.Length); br.Close(); fs.Close(); //存⼊ SqlConnection myConn = new SqlConnection("Data Source=.;Initial Catalog=stumanage;User ID=sa;Password=123"); string strComm = " INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )";//操作数据库语句根据需要修改 SqlCommand myComm = new SqlCommand(strComm, myConn); myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length); myComm.Parameters["@photoBinary"].Value = photo; myConn.Open(); if (myComm.ExecuteNonQuery() > 0) { bel1.Text = "ok"; } myConn.Close(); 读取: ...连接数据库字符串省略 mycon.Open(); SqlCommand command = new SqlCommand("select stuimage from stuInfo where stuid=107", mycon);//查询语句根据需要修改 byte[] image = (byte[])command.ExecuteScalar (); //指定从数据库读取出来的图⽚的保存路径及名字 string strPath = "~/Upload/zhangsan.JPG"; string strPhotoPath = Server.MapPath(strPath); //按上⾯的路径与名字保存图⽚⽂件 BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate)); bw.Write(image); bw.Close(); //显⽰图⽚ this.Image1.ImageUrl = strPath; //采⽤这两种⽅式可以根据实际需求灵活选择。

如何使用MySQL进行图像和多媒体数据的存储

如何使用MySQL进行图像和多媒体数据的存储

如何使用MySQL进行图像和多媒体数据的存储MySQL是一种常用的关系型数据库管理系统,广泛应用于各种应用和领域。

它提供了丰富的功能和灵活的存储选项,包括图像和多媒体数据的存储。

本文将探讨如何使用MySQL来有效地存储和管理图像和多媒体数据,以提高应用程序的性能和用户体验。

1. 导入图像和多媒体数据在MySQL中存储图像和多媒体数据的第一步是将这些数据导入到数据库中。

可以通过多种方式实现这一目标,其中一种常用的方法是使用BLOB类型。

BLOB是Binary Large Object的缩写,它允许将二进制数据以字节的形式存储在数据库中。

为了导入图像和多媒体数据,可以使用MySQL提供的LOAD_FILE()函数。

该函数可以将文件中的数据读取为二进制字符串,并将其插入到BLOB列中。

下面是一个示例代码:```INSERT INTO media_data (id, data)VALUES (1, LOAD_FILE('/path/to/image.jpg'));```在上述示例中,media_data是包含BLOB列的表名,id是数据的唯一标识符,data是BLOB列的名称。

通过指定正确的文件路径,可以将图像或多媒体文件插入到数据库中。

2. 使用合适的数据类型和存储格式除了BLOB类型外,MySQL还提供了其他几种数据类型和存储格式,用于存储图像和多媒体数据。

选择正确的数据类型和存储格式可以提高存储效率和访问性能。

一种常见的选择是使用VARCHAR类型存储图像和多媒体数据的URL或文件路径。

通过存储URL或文件路径,可以避免在数据库中存储大型二进制数据。

这种方法适用于将图像和多媒体数据存储在文件系统中,而不是直接存储在数据库中。

另一种选择是使用MEDIUMBLOB或LONGBLOB类型存储二进制数据。

MEDIUMBLOB可以存储最大为16MB的二进制数据,而LONGBLOB可以存储最大为4GB的二进制数据。

图片存入mySql数据库

图片存入mySql数据库

我在程序代码里贴了向Mysql数据库写入image代码的程序,可是好多人都是Java的初学者,对于这段代码,他们无法将它转换成jsp,所以我在这在写一下用jsp怎样向数据库写入图像文件。

大家先在数据库建这样一张表,我下面的这些代码对任何数据库都通用,只要支持blob类型的只要大家将连接数据库的参数改一下就可以了。

SQL>create table image(id int,content varchar(200),image blob);如果在sqlserver2000的数据库中,可以将blob字段换为image类型,这在SqlServer2000中是新增的。

testimage.html文件内容如下:<HTML><HEAD><TITLE>Image File </TITLE><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></HEAD><FORM METHOD=POST ACTION="testimage.jsp"><INPUT TYPE="text" NAME="content"><BR><INPUT TYPE="file" NAME="image"><BR><INPUT TYPE="submit"></FORM><BODY></BODY></HTML>我们在Form的action里定义了一个动作testimage.jsp,它的内容如下:<%@ page contentType="text/html;charset=gb2312"%><%@ page import="java.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%><html><body><%Class.forName("org.gjt.mm.mysql.Driver").newInstance();Stringurl="jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding= 8859_1";//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改Connection conn= DriverManager.getConnection(url);String content=request.getParameter("content");String filename=request.getParameter("image");FileInputStream str=new FileInputStream(filename);String sql="insert into test(id,content,image) values(1,?,?)"; PreparedStatement pstmt=dbconn.conn.prepareStatement(sql);pstmt.setString(1,content);pstmt.setBinaryStream(2,str,str.available());pstmt.execute();out.println("Success,You Have Insert an Image Successfully");%>下面我写一个测试image输出的例子看我们上面程序写的对不对,testimageout.jsp的内容如下:<%@ page contentType="text/html;charset=gb2312"%><%@ page import="java.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%><html><body><%Class.forName("org.gjt.mm.mysql.Driver").newInstance();Stringurl="jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding= 8859_1";//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改Connection conn= DriverManager.getConnection(url);String sql = "select image from test where id=1";Statement stmt=null;ResultSet rs=null;try{stmt=conn.createStatement();rs=stmt.executeQuery(sql);}catch(SQLException e){}try {while(rs.next()) {res.setContentType("image/jpeg");ServletOutputStream sout = response.getOutputStream();InputStream in = rs.getBinaryStream(1);byte b[] = new byte[0x7a120];for(int i = in.read(b); i != -1;){sout.write(b);in.read(b);}sout.flush();sout.close();}}catch(Exception e){System.out.println(e);}%></body></html>你运行这个程序,你就会看到刚才你写入美丽的图片就会显示在你面前。

图片或文件在数据库存储

图片或文件在数据库存储

图⽚或⽂件在数据库存储对于图⽚或者⽂件的存储,⽬前主要两种⽅式:1.把图⽚直接以⼆进制形式存储在数据库中; ⼀般数据库提供⼀个⼆进制字段来存储⼆进制数据。

⽐如mysql中有个blob字段。

oracle数据库中是blob或bfile类型。

2.图⽚存储在磁盘上,数据库字段中保存的是图⽚的路径;下⾯详细介绍⼀下这两种存储⽅式。

⼀、图⽚以⼆进制形式直接存储在数据库中: 1.存储实现: ⼤体思路: (1)、将读取到的图⽚⽤程序转化成⼆进制形式; (2)、结合insert into 语句插⼊数据表中的blob类型(bfile类型)字段中去。

(3)、从数据库取出图⽚展⽰的时候。

则是直接发送图⽚内容 2.关于mysql中的blob类型 bolb像int型那样,分为blob、MEDIUMBLOB、LONGBLOB。

其实就是从⼩到⼤, blob 容量为64KB ,MEDIUMBLOB 容量为16M,LONGBLOB 容量为4G。

通常是采⽤语⾔的serialize()函数,将对象序列化以后,存⼊该类型的。

(serialize()返回字符串,此字符串包含了表⽰value的字节流,可以存储于任何地⽅)。

3. 缺点 (1).占⽤与mysql交互的通信时间; (2).图⽚⼀般⽐较⼤,超过1M后,还需要修改mysql中限制通信数据⼤⼩的配置 (3).影响数据库性能,导致限制了整个程序的性能; 4.优点 (1).备份图⽚数据和迁移数据⽅便 图⽚以⼆进制形式存储在数据库,有⼀个好处:备份的时候⽅便。

直接备份数据库,图⽚也跟着备份。

换句话说,迁移环境的时候是⽅便。

⽽图⽚放在磁盘上的话,数据库中存储的只是图⽚路径。

备份数据库后。

磁盘上的图⽚也要跟着备份才⾏。

但是,备份这个好处不是很明显。

图⽚在磁盘上,备份磁盘也没很⼤的事情。

打包压缩也可以了。

互联⽹环境毕竟与传统的软件开发不同,web开发⽐较关注⽹站速度。

也就是数据库的速度。

就像互联⽹开发中,有时候为了速度,⽤空间换时间的做法⽐较普遍,所以往往在设计数据库的时候并不⼀定遵循传统数据库设计三⼤范式。

MySQL简单的存储图片信息

MySQL简单的存储图片信息
2、 打 开 存 储 图 片 路 径
1 fp = open("./1.jpg") 2 img = fp.read() 3 fp.close()
3、 存 储 图 片
1 def insert_imgs(img): 2 # mysql连接 3 4 cursor = conn.cursor() 5 # 注意使用Binary()函数来指定存储的是二进制 6 # cursor.execute("insert into img set imgs='%s'" % mysql.Binary(img)) 7 cursor.execute("Insert into img(imgs) values(%s)", (mysql.Binary(img))) 8 # 如果数据库没有设置自动提交,这里要提交一下 9 mit() 10 cursor.close() 11 # 关闭数据库连接 12 conn.close()
4、 提 取 图 片
1 def select_imgs(img): 2 cursor=conn.cursor() 3 cursor.execute('select imgs from img') 4 print cursor.fetchall() 5 cursor.close() 6 conn.close()
此国产分布式函数调度框架从用法调用难度用户所需代码量超高并发性能qps控频精确程度支持的中间件类型任务控存 储 图 片 信 息
MySQL存储图片的二进制,其字段设置为blob属性,二进制数据
1、 连 接 数 据 库
1 import pymysql 2 import sys 3 4 conn=pymysql.connect(host='localhost',user='root',passwd='xxx',db='mydata')
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

一、写一个存储过程,将图片存入数据库中
基本情况介绍:
数据库版本:oracle 11g
数据库用户:scott
数据库密码:tiger
JDK:1.6
要导入的图片:D:\picture\1.jpg
--创建存储图片的表
CREATE TABLE IMAGE_LOB (T_ID V ARCHAR2 (5) NOT NULL,T_IMAGE BLOB NOT NULL);
--创建存储图片的目录
CREATE OR REPLACE DIRECTORY IMAGES AS 'D:\picture';
存储过程如下:
CREATE OR REPLACE PROCEDURE IMG_INSERT (TID V ARCHAR2,FILENAME V ARCHAR2) AS
F_LOB BFILE;--文件类型
B_LOB BLOB;
BEGIN
iNSERT INTO IMAGE_LOB (T_ID, T_IMAGE)
V ALUES (TID,EMPTY_BLOB ()) RETURN T_IMAGE INTO B_LOB;
--插入空的blob
F_LOB:= BFILENAME ('IMAGES', FILENAME);
--获取指定目录下的文件
DBMS_LOB.FILEOPEN(F_LOB, DBMS_LOB.FILE_READONL Y);
--以只读的方式打开文件
DBMS_LOB.LOADFROMFILE (B_LOB, F_LOB,DBMS_LOB.GETLENGTH (F_LOB));
--传递对象
DBMS_LOB.FILECLOSE (F_LOB);
--关闭原始文件
COMMIT;
END;
--将该图片存入表
call IMG_INSERT('1','1.gif'); 验证一下是否已存入:
二、从数据库读取图片并显示在页面上
项目名称为ShowPhoto
启动Tomcat,在浏览器输入:http://localhost:8080/ShowPhoto/,显示如下:。

相关文档
最新文档