Java實現用Mysql存取圖片操作執行個體_java

來源:互聯網
上載者:User

1.MySQL中的BLOB類型

  Mysql中可以儲存大檔案資料,一般使用的BLOB對象。如圖片,視頻等等。

  BLOB是一個二進位大對象,可以容納可變數量的資料。因為是二進位對象,所以與編碼方式無關。有4種BLOB類型:TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB。它們只是可容納值的最大長度不同。

  四種欄位類型儲存的最大長度如下:

複製代碼 代碼如下:

  TINYBLOB - 255 bytes
  BLOB - 65535 bytes(64KB)
  MEDIUMBLOB - 16,777,215 bytes(16MB) (2^24 - 1)
  LONGBLOB - 4G bytes (2^32 – 1)

2.java對MySQL圖片的讀取

下面是test資料庫中定義的phototest表結構。

儲存與讀取圖片的代碼如下:

import java.io.*;import java.sql.*;public class LoadStoreBLOB { public static void main(String[] args) {  DBConnection  DB = new DBConnection(); //負責串連MySQl資料庫的類  Connection   con = null;  PreparedStatement  ps = null;  ResultSet  rs = null;  InputStream in = null;   try {   //從本地硬碟硬碟讀取一張圖片儲存到資料庫   con=DB.getConn();   in=new FileInputStream("sdf.png");   ps=con.prepareStatement("insert into test.phototest values(?,?)");   ps.setInt(1,2);   ps.setBinaryStream(2, in, in.available());   ps.executeUpdate();   in.close();   DB.closeConn(con);      //從資料庫讀取圖片儲存到本地硬碟   con=DB.getConn();   ps=con.prepareStatement("select * from test.phototest where id=?");   ps.setInt(1,2);   rs=ps.executeQuery();   rs.next(); //將游標指向第一行   in=rs.getBinaryStream("photo");   byte[] b=new byte[in.available()]; //建立儲存圖片資料的byte數組   in.read(b);   OutputStream out=new FileOutputStream("222.jpg");   out.write(b);   out.flush();   out.close();   DB.closeConn(con);  }   catch (Exception e) {   System.out.println("Error::"+e);  } }}

3.選擇合適的欄位大小

  如果選擇的欄位類型的最大長度較小,放不下儲存的資料,可能會報出MySQL資料截斷異常。如:

複製代碼 代碼如下:

    com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'photo' at row 1

 

Mysql 中文參考手冊列類型:

  http://dev.mysql.com/doc/refman/5.1/zh/column-types.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.