java把圖片儲存到資料庫中的例子

來源:互聯網
上載者:User

例子代碼


Class.forName("com.mysql.jdbc.Driver");

 //System.out.print("載入驅動完畢");

 String url="jdbc:mysql://localhost:3306/studentmanager";

 String username="root";

 String password="root";

 String sql1="select * from images";

 Connection conn=DriverManager.getConnection(url,username,password);

 //建立一個 Statement 對象來將 SQL 陳述式發送到資料庫。

 PreparedStatement pst=conn.prepareStatement(sql1);

 ResultSet rs=pst.executeQuery();

 

 rs.next();

 //從ResultSet中得到Blob的對象

 Blob b=rs.getBlob("img");

 //通過Blob對象的getBinaryStream得到位元組流

 InputStream fis= b.getBinaryStream();

 //構建位元組流的緩衝BufferedInputStream的對象

 BufferedInputStream bis=new BufferedInputStream(fis);

 //準備一個FileOutputStream輸出資料流對象

 FileOutputStream fos =new FileOutputStream("d://2.jpg");

 //準備一個位元組數組,以備緩衝讀對象BufferedInputStream,每次讀這些位元組長度

 byte[] be=new byte[1024];

 //每讀1024個位元組就向FileOutputStream寫1024個位元組,直到寫完。

 while((bis.read(be))!=-1){

 fos.write(be);

 }

 fos.flush();

 fos.close();

 fis.close();

 bis.close();

 } catch (Exception ex) {

ex.printStackTrace();

}

 

 }

 

 public void write(){

 try {

 Class.forName("com.mysql.jdbc.Driver");

 //System.out.print("載入驅動完畢");

 String url="jdbc:mysql://localhost:3306/studentmanager";

 String username="root";

 String password="root";

 String sql1="insert into images values (?)";

 Connection conn=DriverManager.getConnection(url,username,password);

 //建立一個 Statement 對象來將 SQL 陳述式發送到資料庫。

 PreparedStatement pst=conn.prepareStatement(sql1);

 File file=new File("e://1.jpg");

 int len=(int)file.length();

 FileInputStream fis=new FileInputStream(file);

 pst.setBinaryStream(1,fis,len);

 int count=pst.executeUpdate();

if(count>0){

System.out.println("執行成功");

}else{

 System.out.println("執行未返回任何影響行數");

}

 

 } catch (Exception ex) {

ex.printStackTrace();

}

其實就是以二進位形式儲存在資料庫了,此方法不推薦了因為資料多了不方便處理了並且資料庫會很大查詢也比較慢了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.