JDBC 2.0 引進(jìn)了對應(yīng)于SQL_99的許多新對象,這些新對象有BLOB,CLOB,ARRAY,REF,結(jié)構(gòu)化類型,DISTINCT類型以及LOCATOR.
JDBC 3.0增加了Boolean和Datalink對象
插入這些高級數(shù)據(jù)類型到數(shù)據(jù)庫中的主要手段是使用PReparedStatement對象,讀取主要是ResultSet對象.下面介紹怎么在數(shù)據(jù)庫中讀取和寫入高級數(shù)據(jù)類型
1:BLOB和CLOB
BLOB: 二進(jìn)制大對象(Binary Large OBject)即一個字節(jié)序列(比喻說一個mp3文件可以存儲為一個BLOB)
CLOB:一個對VARCHAR 或類似的列來說太長的字符串.
來自數(shù)據(jù)庫的BLOB和CLOB數(shù)據(jù)可以通過java.sql.Blob和java.sql.clob對象來操作.
ResultSet 和PreparedStatement對象提供的處理這兩種數(shù)據(jù)的方法如下
ResultSet : PreparedStatement
Blob getBlob(int) void setBlob(int ,Blob)//第一個參數(shù)是PreparedStatement中的占位符的索引,以下相同
Blob getBlob(string) void setClob(int ,Clob)
Clob getClob(int)
Clob getClob(String)
使用PreparedStatement.setBlob(int,Blob)我們可以用BLOB數(shù)據(jù)來設(shè)置預(yù)備語句中的占位符,并且可以通過執(zhí)行SQL語句把這些數(shù)據(jù)寫入到另一個表中
如:
String sql="select blob_col from blob_table where id=?"http://blob_colum ,id為blob_table 這個表的列名
PreparedStatement ps=connection.prepareStatement(sql);
ps.setInt(1,1);
ResultSet rset=ps.executeQuery();
Blob blob=null;
if(rset.next())
{
blob=rset.getBlob(1);
}
上敘中blob只是持有一個指向數(shù)據(jù)庫中這些二進(jìn)制數(shù)據(jù)的引用.并不持有實(shí)際二進(jìn)制數(shù)據(jù),然后代碼可以使用這個相同的引用把這些二進(jìn)制數(shù)據(jù)寫入到另外的一個表中:
sql="insert into blob_table_2 values(?)";
ps=connection.prepareStatement(sql);
ps.setBlob(1,blob);
ps.executeUpdate();
jdbc 2.0中的BLOB和CLOB借口提供了一種從數(shù)據(jù)庫中獲取數(shù)據(jù)或?qū)憯?shù)據(jù)到數(shù)據(jù)庫的手段,這個手段是通過從數(shù)據(jù)庫中獲得一個流(輸入或者輸出)對象.并從該流中讀取數(shù)據(jù)或?qū)懭?
例:
OutputStream out=null;
BufferedInputStream in=null;
File file=new File("****");
ReslutSet rset=statement.executeQuery(sql);//從查詢語句中取得一個結(jié)果集
if(rset.next())
{
Blob blob=rset.getBlob(1);
out=((Oracle.sql.Blob)blob).getBinaryOutputStream();//jdbc 2.0不支持寫數(shù)據(jù)到blob,因此我們用Oracle的擴(kuò)展
int bufferSize==((oracle.sql.Blob)blob).getBufferSize();
in=new BufferedInputStream(new fileInputStream(file),bufferSize);
byte[] b=new byte[bufferSize];
int count=in.read(b,0,bufferSize);
//開始存儲數(shù)據(jù)到數(shù)據(jù)庫中
while(cout!=-1)
{
out.write(b,o,count);
cout=in.read(b,o,bufferSize);
}
//數(shù)據(jù)寫完
out.close();
in.close();
connection.commit();//提交改變
........
}
類似的,我們可以從blob中得到一個輸入流,把blob數(shù)據(jù)寫入到文件中去
InputStream in=blob.getBinaryStream();
int bufferSize =((oracle.sql.Blob)blob).getBufferSize();
新聞熱點(diǎn)
疑難解答