前些天写了几个录入图片的方法,不是很完善,还有点小问题,在这里贴出来,希望给需要的朋友带来些便利!
方法一、代码如下:
public
void updatePhoto()
throws Exception{
Connection conn = MyCon.getCon();
File file = new File( "c:/yflower.gif");
InputStream input = new FileInputStream(file);
String sql = "UPDATE SHOW.DEPT_INFO SET PICTURE2=? WHERE ID=445";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setBinaryStream(1, input, Integer.parseInt(String.valueOf(file.length())));
int count = pstm.executeUpdate();
if(count>0){
System.out.println( "--------------成功更新图片!");
}
pstm.close();
input.close();
}
Connection conn = MyCon.getCon();
File file = new File( "c:/yflower.gif");
InputStream input = new FileInputStream(file);
String sql = "UPDATE SHOW.DEPT_INFO SET PICTURE2=? WHERE ID=445";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setBinaryStream(1, input, Integer.parseInt(String.valueOf(file.length())));
int count = pstm.executeUpdate();
if(count>0){
System.out.println( "--------------成功更新图片!");
}
pstm.close();
input.close();
}
此代码有些问题,只能存放小图片,插入大图片时会报错!
方法二、代码如下:
public void updatePhoto2() throws Exception{
Connection conn = MyCon.getCon();
conn.setAutoCommit( false);
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery( "SELECT PICTURE2 FROM SHOW.DEPT_INFO WHERE ID=445 FOR UPDATE");
oracle.sql.BLOB blob= null;
if (rs.next()){
blob=(oracle.sql.BLOB) rs.getBlob( "PICTURE2");
System.out.println( "==========="+blob);
}
OutputStream outStream= null;
if(blob== null){
}
outStream = blob.getBinaryOutputStream();
File file = new File( "C:/Documents and Settings/Administrator/桌面/aaa/b.jpg");
InputStream fin = new FileInputStream(file);
// 将输入流写到输出流
byte[] b = new byte[blob.getBufferSize()];
int len = 0;
while ( (len = fin.read(b)) != -1) {
outStream.write(b, 0, len);
}
fin.close();
outStream.flush();
outStream.close();
conn.commit();
conn.close();
}
感谢您的支持!我会将代码更加完善,并共享出来!
转载于:https://blog.51cto.com/rhyme/77024