select student_seq.nextval from dual // 每执行一次都不一样(不管数据库插没插入数据)
public class OracleConnection {
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="zw";
String password="pass";
public Connection getConnection(){
Connection conn=null;
try {
Driver.class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn=DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
public class ShowImageServlet extends HttpServlet {//读Blob
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
OracleConnection oc=new OracleConnection();
Connection conn=oc.getConnection();
OutputStream out=resp.getOutputStream();
String sl="select image from student where id=16 ";// image 类型Blob
PreparedStatement ps2;
try {
ps2 = conn.prepareStatement(sl);
ResultSet rs2=ps2.executeQuery();
Blob b=null;
byte[] buf=new byte[1024];
BufferedOutputStream bos=null;
BufferedInputStream bis=null;
if(rs2.next()){
b=rs2.getBlob("image");
bis=new BufferedInputStream(b.getBinaryStream());
while(bis.read(buf)!=-1){
out.write(buf);
out.flush();
}
bis.close();
}
rs2.close();
ps2.close();
conn.close();
out.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
------------------------------------------------------------------------
public int updateBlob(){ //插入Blob
int i=-1;
Blob b=null;
OracleConnection oc=new OracleConnection();
Connection conn=oc.getConnection();
try {
String sl="select image from student where id=47 for update";
PreparedStatement ps2=conn.prepareStatement(sl);
ResultSet rs2=ps2.executeQuery();
//System.out.println(rs2.next());
byte[] buf=new byte[1024];
if(rs2.next()){
b=rs2.getBlob("image"); //数据库初始为empty_blob();
System.out.println(b);
BufferedOutputStream bos=new BufferedOutputStream(b.setBinaryStream(0));
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(fileName));//blob对象
while(bis.read(buf)!=-1){
bos.write(buf); //blob对象保存到数据库
}
bos.close();
bis.close();
}
rs2.close();
ps2.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return i;
}
------------------------------------------------------------------------------------
Clob对象的插入:(对照上面的需要更改的地方:)
BufferedWriter bos=new BufferedWriter(b.setCharacterStream(0));
BufferedReader bis=new BufferedReader(new FileReader(fileName));
char[] buf=new char[1024];
String sql="insert into student(id,name,comm) values(?,?,empty_clob())";
Clob b=null;
http://hi.baidu.com/%C1%F5%D0%A1%BB%A2%C1%F5/blog/item/28ddd2c75cc93fd6d0006076.html