oracle的blob字段比较特殊,他比long字段的性能要好很多,可以用来保存例如图片之类的二进制数据。
写入blob字段和写入 其它类型字段的方式非常不同,因为blob自身有一个cursor,你必须使用cursor对blob进行操作,因而你在写入blob之前,必须获得cursor才 能进行写入,那么如何获得blob的cursor呢?
这需要你先插入一个empty的blob,这将创建一个blob的cursor,然后你再把这个 empty的blob的cursor用select查询出来,这样通过两步操作,你就获得了blob的cursor,可以真正的写入blob数据了。
看下面的 jdbc的demo,把oraclejdbc.jar这个二进制文件的content字段(这是一个blob型字段)
import java.sql.*;
import java.io.*;
import oracle.sql.*;
public class writeblob {
public static void main(string[] args) {
try {
drivermanager.registerdriver(new oracle.jdbc.driver.oracledriver());
connection conn = drivermanager.getconnection("jdbc:oracle:thin:@localhost:1521:orcl","fankai","fankai");
conn.setautocommit (false);
blob blob = null;
preparedstatement pstmt = conn.preparestatement("insert into javatest (name,content) values(?,empty_blob())");
pstmt.setstring(1,"fankai");
pstmt.executeupdate();
pstmt.close();
pstmt = conn.preparestatement("select content from javatest where name= ? for update");
pstmt.setstring(1,"fankai");
resultset rset = pstmt.executequery();
if (rset.next()) blob = (blob) rset.getblob(1);
string filename = "oraclejdbc.jar";
file f = new file(filename);
fileinputstream fin = new fileinputstream(f);
system.out.println("file size = " + fin.available());
pstmt = conn.preparestatement("update javatest set content=? where name=?");
outputstream out = blob.getbinaryoutputstream ();
int count = -1, total = 0;
byte[] data = new byte[(int)fin.available()];
fin.read(data);
out.write(data);
/*
byte[] data = new byte[blob.getbuffersize()]; 另一种实现方法,节省内存
while ((count = fin.read(data)) != -1) {
total += count;
out.write(data, 0, count);
}
*/
fin.close();
out.close();
pstmt.setblob(1,blob);
pstmt.setstring(2,"fankai");
pstmt.executeupdate();
pstmt.close();
conn.commit();
conn.close();
} catch (sqlexception e) {
system.err.println(e.getmessage());
e.printstacktrace();
} catch (ioexception e) {
system.err.println(e.getmessage());
}
}
}
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器