日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java数据库编程——Insert and Retrieve Images from MySql Table Using Java

發布時間:2023/12/3 java 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java数据库编程——Insert and Retrieve Images from MySql Table Using Java 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【0】README 0.1)本文翻譯自?http://harmeetsingh13.blogspot.jp/2013/03/insert-and-retrieve-images-from-mysql.html
【1】正文如下: 段1)演示 從數據庫表中插入和查詢出圖片。大多數情況下,圖片數據都存儲在數據庫外部的一些文件夾下,而將其路徑存儲到數據庫。但是在一些場景下,我們需要將圖片以二進制數據格式存儲到數據庫。 Create Table in MySQL : CREATE TABLE `image` (`id` varchar(45) DEFAULT NULL,`size` int(11) DEFAULT NULL,`image` longblob );
段2)?在mysql中,我們使用blob 類型存儲這樣類型的數據。它 只支持5kb 的圖片數據容量,但這也取決于數據庫提供商。?
【2】代碼示例 2.1)向數據庫插入圖片 import java.sql.*; import java.io.*; public class InsertImagesMysql{public static void main(String[] args){System.out.println("Insert Image Example!");String driverName = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/";String dbName = "test";String userName = "root";String password = "root";Connection con = null;try{Class.forName(driverName);con = DriverManager.getConnection(url+dbName,userName,password);Statement st = con.createStatement();File imgfile = new File("pic.jpg");FileInputStream fin = new FileInputStream(imgfile);PreparedStatement pre =con.prepareStatement("insert into Image values(?,?,?)");pre.setString(1,"test");pre.setInt(2,3);pre.setBinaryStream(3,(InputStream)fin,(int)imgfile.length());pre.executeUpdate();System.out.println("Successfully inserted the file into the database!");pre.close();con.close(); }catch (Exception e1){System.out.println(e1.getMessage());}} }
2.2)從數據庫查詢圖片并保存到本地 import java.sql.*; import java.io.*; public class RetriveImagesMysql{public static void main(String[] args){System.out.println("Retrive Image Example!");String driverName = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/";String dbName = "test";String userName = "root";String password = "root";Connection con = null;try{Class.forName(driverName);con = DriverManager.getConnection(url+dbName,userName,password);Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery("select image from image");int i = 0;while (rs.next()) {InputStream in = rs.getBinaryStream(1);OutputStream f = new FileOutputStream(new File("test"+i+".jpg"));i++;int c = 0;while ((c = in.read()) > -1) {f.write(c);}f.close();in.close();}}catch(Exception ex){System.out.println(ex.getMessage());}} }

總結

以上是生活随笔為你收集整理的java数据库编程——Insert and Retrieve Images from MySql Table Using Java的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。