Clob和blob的操作主要分为3种:插入,更新和读取显示。
对于插入,可以分为两类。一类是可以直接按照正常的字段处理,一类为必须先插入空clob/blob再更新为真正的内容。
插入:
对于大部分的数据库,在插入lob时都可以通过PreparedStatement.setAsciiStream或PreparedStatement.setBinaryStream直接写入,查到的资料包括:
H2数据库:http://code.google.com/p/h2database/issues/detail?id=100#c3
Mysql数据库:http://lavasoft.blog.51cto.com/62575/64963
DB2:http://lavasoft.blog.51cto.com/62575/64683
而对于Oracle数据库则必须先插入空lob,重新查询再进行更新(查询时需要加forupdate)。方法如下:
Oracle数据库:http://www.iteye.com/topic/254
插入空Lob的方式很多,如可以插入长度为1的byte[1到blob中]或1个字符的字符串到clob中。也可以在创建表时通过defaultempty_clob()由数据库自动创建。
对于上面帖子的补充:robbin同志介绍说需要加forupdate行锁,是为了防止被其他连接并发更新,这种提法并不完整。oracle数据库要求进行lob更新时,必须加forupdate,否则报错,这是数据库一个强制要求。就算你知道不会有并发修改,也必须加。
对于Lob更新,方法都比较类似,查询到Lob字段然后直接更新(H2不支持Lob字段的更新)。需要注意的是,获取到Lob的Stream(如:Blob.setBinaryStream())写入完毕后,必须调用flush(),否则可能会出现数据丢失(在Oracle10g+odbc14.jar下测试发现)。
对于Lob读取:可以使用传统的java.sql.Clob/java.sql.Blob的api,某些驱动也可以使用rs.getString()或rs.getBytes()(没有测试过,据说大部分都行)当成普通的varchar和字节字段处理,很是方便。
对于Clob/Blob的使用,大部分都纠结在Oracle上,Oracle有各种各样的限制,如经典的长度限制,最新的odbc14.jar驱动据说已经解决了所有问题,也就是增加一个连接参数SetBigStringTryClob的事情。相关的资料如下:
Oracle官方文档:
http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jdbc/clob10g/handlingclobsinoraclejdbc10g.html
也可以看看一大堆跟贴的讨论:
http://www.iteye.com/topic/254
我没有测试过rs.getString()的方法,我测试过Oracle和H2的Clob api。通过clob api的方法,可以正常的写入和读取100万字符的大字符串。最理想,最节省内存,也最通用的应该还是JDBC为Lob设计的api。NAMEvarchar(24)DEFAULTNULL,
TXTtext,
IMGblob
) ENGINE=InnoDB DEFAULT CHARSET=gbk;importjava.sql.*;
importjava.io.*;
/**
*JDBC读取MySQLlob字段测试
*File:TestLob4MySQL.java
*User:leizhimin
*Date:2008-3-314:44:30
*/
publicclassTestLob4MySQL{
publicstaticfinalStringurl="jdbc:mysql://localhost/testdb";
publicstaticfinalStringusername="root";
publicstaticfinalStringpassword="leizhimin";
publicstaticfinalStringdriverClassname="com.mysql.jdbc.Driver";
/**
*数据库连接获取器
*
*@return数据库连接
*/
publicstaticConnectionmakeConnection(){
Connectionconn=null;
try{
Class.forName(driverClassName);
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
try{
conn=DriverManager.getConnection(url,username,password);
}catch(SQLExceptione){
e.printStackTrace();
}
returnconn;
}
/**
*测试数据库连接
*/
publicstaticvoidtestConnection(){
Connectionconn=makeConnection();
try{
Statementstmt=conn.createStatement();
ResultSetrs=stmt.executeQuery("SELECT*FROMmysql.user");
while(rs.next()){
Strings1=rs.getString(1);
System.out.println(s1);
}
rs.close();
stmt.close();
}catch(SQLExceptione){
e.printStackTrace();
}finally{
try{
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
/**
*插入Lob字段
*/
publicstaticvoidtestInsertlob(){
Connectionconn=makeConnection();
try{
conn.setAutoCommit(false);
FiletxtFile=newFile("C:\\txt.txt");
FileimgFile=newFile("C:\\img.png");
inttxt_len=(int)txtFile.length();
intimg_len=(int)imgFile.length();
try{
InputStreamfis1=newFileInputStream(txtFile);
InputStreamfis2=newFileInputStream(imgFile);
PreparedStatementpstmt=conn.prepareStatement("INSERTINTOT_LOB(NAME,TXT,IMG)VALUES('G',?,?)");
pstmt.setAsciiStream(1,fis1,txt_len);
pstmt.setBinaryStream(2,fis2,img_len);
pstmt.executeUpdate();
conn.commit();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
}catch(SQLExceptione){
e.printStackTrace();
}finally{
try{
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
/**
*读取lob字段
*/
publicstaticvoidtestQueryLob(){
Connectionconn=makeConnection();
try{
conn.setAutoCommit(false);
Statementstmt=conn.createStatement();
ResultSetrs=stmt.executeQuery("SELECTTXT,IMGFROMT_LOB");
inti=1;
while(rs.next()){
Clobclob=rs.getClob("TXT");
Blobblob=rs.getBlob("IMG");
InputStreamtxtIs=rs.getAsciiStream("TXT");
InputStreamimgIs=rs.getBinaryStream("IMG");
InputStreamReadertxtIsr=newInputStreamReader(txtIs);
InputStreamReaderimgIsr=newInputStreamReader(imgIs);
BufferedReaderbuff_txtIsr=newBufferedReader(txtIsr);
BufferedReaderbuff_imgIsr=newBufferedReader(imgIsr);
Stringline=null;
while(null!=(line=buff_txtIsr.readLine())){
System.out.println(line);//将其输出至屏幕,实际你可以按照需要处理
}
FilefileOutput=newFile("c:\\img_x"+i+".png");
FileOutputStreamfo=newFileOutputStream(fileOutput);
intc;
while((c=imgIs.read())!=-1)
fo.write(c);
fo.close();
System.out.println("img"+i+"retrieved!");
i++;
}
conn.commit();
}catch(SQLExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
/**
*读取lob字段
*/
publicstaticvoidtestQueryLob1(){
Connectionconn=makeConnection();
try{
conn.setAutoCommit(false);
Statementstmt=conn.createStatement();
ResultSetrs=stmt.executeQuery("SELECTTXT,IMGFROMT_LOB");
while(rs.next()){
Clobclob=rs.getClob("TXT");
Blobblob=rs.getBlob("IMG");
InputStreamtxtIs=clob.getAsciiStream();
InputStreamimgIs=blob.getBinaryStream();
InputStreamReadertxtIsr=newInputStreamReader(txtIs);
InputStreamReaderimgIsr=newInputStreamReader(imgIs);
BufferedReaderbuff_txtIsr=newBufferedReader(txtIsr);
BufferedReaderbuff_imgIsr=newBufferedReader(imgIsr);
Stringline=null;
while(null!=(line=buff_txtIsr.readLine())){
System.out.println(line);//将其输出至屏幕,实际你可以按照需要处理
}
}
conn.commit();
}catch(SQLExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
/**
*删除lob字段
*/
publicstaticvoidtestDeleteLob(){
Connectionconn=makeConnection();
try{
conn.setAutoCommit(false);
Statementstmt=conn.createStatement();
introw=stmt.executeUpdate("DELETEFROMT_LOB");
conn.commit();
System.out.println("删除"+row+"行数据!");
}catch(SQLExceptione){
e.printStackTrace();
}finally{
try{
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
/**
*读取lob字段
*/
publicstaticvoidtestUpdateLob(){
Connectionconn=makeConnection();
try{
Stringin_str="HAHAHAHAHAHA!!!";
Filein_file=newFile("c:\\img_haha.png");
InputStreamtxt_is=string2InputStream(in_str);
InputStreamimg_is=newFileInputStream(in_file);
conn.setAutoCommit(false);
PreparedStatementpstmt=conn.prepareStatement("UPDATET_LOBSETTXT=?,IMG=?WHERENAME='G'");
pstmt.setAsciiStream(1,txt_is,in_str.getBytes().length);
pstmt.setBinaryStream(2,img_is,(int)in_file.length());
introw=pstmt.executeUpdate();
conn.commit();
txt_is.close();
img_is.close();
//System.out.println("更新"+row+"行数据!");
}catch(SQLExceptione){
e.printStackTrace();
}catch(FileNotFoundExceptione){
e.printStackTrace();//TochangebodyofcatchstatementuseFile|Settings|FileTemplates.
}catch(IOExceptione){
e.printStackTrace();//TochangebodyofcatchstatementuseFile|Settings|FileTemplates.
}finally{
try{
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
publicstaticvoidmain(Stringargs[]){
//testInsertlob();
//testQueryLob();
//testQueryLob1();
//testDeleteLob();
testUpdateLob();
}
publicstaticInputStreamstring2InputStream(Stringstr){
if(str==null)returnnull;
returnnewByteArrayInputStream(str.getBytes());
}
publicstaticStringinputStream2String(InputStreamis){
StringBuffersb=newStringBuffer();
BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
StringinputLine;
try{
while((inputLine=br.readLine())!=null){
sb.append(inputLine).append("\n");
}
}catch(IOExceptione){
e.printStackTrace();
}
returnsb.toString();
}
}