package com.lcpan;
/*
* BLOB處理大量資料的資料型態,如圖形、檔案
* (1)使用setBinaryStream寫入資料
* (2)使用getBlob取得資料
*
<一>(1) 一般有加Buffere,代表可以一次寫多個byte
(2) reader 1字元 = 2byte
inputStream 1byte
<二> (1) SQL先建立table,cre_blobtest.sql
(2) Eclipse新增Project(Advanced) -> package(com.lcpan)
(3) Eclipse加入BLOBDemo.java,執行一次(確定有抓到,因為有args[x]) -> run configurations/Arguments標籤
-> Program arguments裡點Variables -> 選string_prompt -> OK (準備設定輸入框)
(4) Advanced專案,新增資料夾res,放入Tomcate.gif
(5) 執行 -> 輸入 res/Tomcat.gif res/Tomcat1.gif
*/
import java.sql.*;
import java.io.*;
public class BLOBDemo {
public static void main(String[] args) throws IOException {
String inFile=args[0]; //檔案來源路徑
String outFile=args[1]; //檔案輸出路徑
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
String Url="jdbc:sqlserver://localhost:1433;databaseName=jdbc";
conn = DriverManager.getConnection(Url,"sa","passw0rd");
//檢查資料庫內是否有資料
String selectsql="select photo from blobtest where name=?";
pstmt=conn.prepareStatement(selectsql);
pstmt.setString(1, inFile);
rs=pstmt.executeQuery();
if(rs.next()){//若有資料則刪除
String delsql="delete from blobtest where name=?";
pstmt=conn.prepareStatement(delsql);
pstmt.setString(1, inFile);
pstmt.executeUpdate();
System.out.println("Delete blob is successful!");
}
//寫入檔案到資料庫
File f=new File(inFile); //取得檔案來源
FileInputStream fis=new FileInputStream(f); //將檔案轉成byte,為了配合底下寫入資料庫的setBinaryStream
String insertsql="insert into blobtest VALUES(?,?) ";
pstmt=conn.prepareStatement(insertsql);
pstmt.setString(1, inFile);//寫入檔案名稱
pstmt.setBinaryStream(2,fis,f.length());//寫入圖片檔
//第一個參數為?的順序,第二個參數為檔案所在位置,第三個參數為檔案的大小
pstmt.executeUpdate();
System.out.println("Insert blob is successful!");
//取出資料庫圖片檔並寫入res資料夾
String selectphoto="select photo from blobtest where name=?";
pstmt=conn.prepareStatement(selectphoto);
pstmt.setString(1, inFile);
rs=pstmt.executeQuery();
if(rs.next()){
FileOutputStream fos=new FileOutputStream(outFile);//檔案要寫入的位置
Blob b = rs.getBlob("photo");//從資料庫取得圖片檔,圖片檔用getBlob取得,並存在Blob型別的b物件
byte[] data=b.getBytes(1,(int) b.length());
//b.getBytes()回傳型別為byte[]
//1代表起始位置,b.length()為檔案大小,回傳值為long,但getBytes()函數的第二個參數只能放int型態,因此必須轉成int型態
//FileOutputStream write方法(byte[],起始位置,檔案大小)
fos.write(data,0,(int)b.length());
fos.close(); //關閉檔案
System.out.println("File output is successful!");
}
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}// end of main()
}// end of class BLOBDemo
文章標籤
全站熱搜
