本想找点代码测试一下在SQL Server中存取图片的方法, 结果狂搜之后才发现,不是基于在jsp中的应用,就是本身过程太复杂,一时半会儿难以看懂,只好自己“亲自”上阵慢慢试了!不曾想原来过程原来是如此之简单!!!基本代码如下:
File f;
JFileChooser chooser=new JFileChooser();
chooser.setCurrentDirectory(new File(".")); //定位当前目录
try {
//***********写入***********************************************************************
if(chooser.showOpenDialog(null)==JFileChooser.CANCEL_OPTION){
System.exit(0);
}
f=chooser.getSelectedFile();
int length=(int)f.length();
InputStream fin=new FileInputStream(f);
//SQL Server中只有image类型可以存储二进制数据
PreparedStatement pstmt=getConn().prepareStatement("INSERT INTO Test(myimage) VALUES(?)");
pstmt.setBinaryStream(1, fin, length);
pstmt.executeUpdate();
pstmt.clearParameters();
pstmt.close();
//***********读出保存为文件***********************************************************
Statement stmt=getConn().createStatement();
ResultSet rs=stmt.executeQuery("SELECT myimage FROM Test");
rs.next();
Blob blob=rs.getBlob(1);
if(chooser.showSaveDialog(null)==JFileChooser.CANCEL_OPTION){
System.exit(0);
}
f=chooser.getSelectedFile();
FileOutputStream fout=new FileOutputStream(f);
fout.write(blob.getBytes(1, (int)blob.length()));
fout.flush();
fout.close();
stmt.close();
//***********用JLabel显示出来********************************************************* Statement stmt=getConn().createStatement(); ResultSet rs=stmt.executeQuery("SELECT myimage FROM Test"); rs.next(); InputStream is=rs.getBinaryStream(1); byte[] b=new byte[is.available()]; is.read(b); ImageIcon icon=new ImageIcon(b); jlbl.setIcon(icon); is.close(); rs.close(); stmt.close(); } catch (FileNotFoundException e) { System.err.println(e.toString()); e.printStackTrace(); } catch (SQLException e) { System.err.println(e.toString()); e.printStackTrace(); } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); }