2013年3月22日 星期五

Java 連接MySQL (三) 存入檔案類型的資料

參自: 語言技術: Java Gossip (二) <<<超連結

在欄位上使用BLOB或CLOB資料型態。
BLOB: Binary Large Object,大量的二進位資料。(JDBC提供Blob類別)
CLOB: Character Large Object,大量的文字資料。(JDBC提供Clob類別)

可以使用的PreparedStatement方法,包括setBinaryStream(),setObject(),setAsciiStream,setUnicodeStream()等。

File file=new File("c:/xsd.jpg");
int length=(int)file.length();
FileInputStream fis=new FileInputStream(file);

PreparedStatement ps=con.prepareStatement("INSERT INTO MovieList VALUES(?,?,?)");
ps.setString(1,"下水道");
ps.setString(2,"2010/10/10");
ps.setBinaryStream(3,fis,length);

ps.executeUpdate();
ps.clearParameters();
ps.close();
fis.close();

取得檔案
Statement st=con.createStatement();
ResultSet resultSet=st.executeQuery("SELECT * FROM MovieList");
resultSet.next();
Blob blob=resultSet.getBlob(3);     搭配blob.getBinaryString(), blob.getBytes()使用
Clob clob=resultSet.getClob(3);     搭配clob.getCharacterStream(), clob.getSubString()使用

寫入檔案
FileOutputStream fos=new FileOutputStream("c:/xsd1.jpg");
fos.write(blob.getBytes(1,(int)blob.length());
fos.flush();
fos.close();

For Oracle
Oracle 9i之前,要先建立Blob/Clob的空欄位以取得Blob/Clob游標。
(i)
PreparedStatement ps=con.prepareStatement("INSERT INTO MovieList(id,des,pic) VALUES(?, EMPTY_CLOB(), EMPTY_BLOB())");
ps.setInt(1,1);
ps.executeUpdate();

(ii)
PreparedStatement ps=con.prepareStatement("INSERT INTO MovieList(id,des,pic) VALUES(?, ?, ?)");
ps.setInt(1,1);
ps.setClob(2,CLOB.empty_lob());
ps.setBlob(3,BLOB.empty_lob());
ps.executeUpdate();

小範例
String driver="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:demo";
String user="ted";
String password="12345";

Class.forName(driver);
Connection con=null;
PreparedStatement ps=null;

con=DriverManager.getConnection(url,user,password);
con.setAutoCommit(false);

//存入Blob/Clob空欄位
ps=con.prepareStatement("INSERT INTO MovieList(id,des,pic) VALUES(?, EMPTY_CLOB(), EMPTY_BLOB())");
ps.setInt(1,1);
ps.executeUpdate();
ps.close();

//查詢Blob/Clob欄位以取得游標
ps=con.prepareStatement("SELECT des,pic FROM MovieList WHERE id=? for update");
ps.setInt(1,1);
ResultSet rs=ps.executeQuery();
rs.next();

Clob clob=(Clob)rs.getClob(1);
Blob blob=(Blob)rs.getBlob(2);

clob.putString(1,"...ABC...");

File file=new File("c:/xsd.jpg");
FileInputStream fis=new FileInputStream(file);
OutputStream os=blob.getBinaryOutputStream();

Byte[] buffer=new Byte[1024];
while(fis.read(buffer) > 0)
      os.write(buffer);
fis.close();
os.close();

ps=con.prepareStatement("UPDATE MovieList SET des=?,pic=? WHERE id=?");
ps.setClob(1,clob);
ps.setBlob(2,blob);
ps.setInt(3,1);
ps.executeUpdate();

ps.close();
con.commit();


沒有留言:

張貼留言