public static void createPhoto(Connection conn,String sql) throws SQLException, IOException{
OutputStream outputStream=null;
ResultSet rs = null;
PreparedStatement ps = null;
try{
CreatPhoto cp = new CreatPhoto();
// 加载驱动程序
cp.loadJdbcDriver();
cp.connect();
sql = "select name,id,content,type from A";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
String s1 = "";
//将图片存放到本地的路径
String s = "E:\\photo";
while (rs.next()) {
System.out.println("名: " + rs.getString("name")+"."+rs.getString("type"));
String temp=rs.getString("name")+"_"+rs.getString("id")+"."+rs.getString("type");
Blob blob = rs.getBlob("content");
if(blob == null){
continue;
}
//验证图片路径是否存在,不存在就创建
File f = new File(s);
if(!f.exists()){
f.mkdirs();
}
s1 = s + "\\"+temp;
File file2 = new File(s1);
outputStream = new FileOutputStream(file2);
try {
//blob.getBytes的第一个参数是从第几个字节开始提取数据,第二个是提取字节的长度
outputStream.write(blob.getBytes(1, (int) blob.length()));
} catch (IOException e) {
e.printStackTrace();
}
}
outputStream.close();
cp.disConnect();
}catch(Exception e){
try{
if(outputStream!=null) outputStream.close();
if(ps!=null) ps.close();
if(rs!=null) rs.close();
if(conn!=null) conn.close();
}catch(Exception e1){
}
e.printStackTrace();
throw new IOException(e.getMessage());
}
}
java实现clob二进制字节转换成图片到本地磁盘
本文介绍了一种从数据库中提取图片数据,并将其保存到本地文件系统的方法。使用Java编程,通过PreparedStatement执行SQL查询,获取Blob类型的数据,然后将这些数据写入到指定的文件路径。文章详细展示了如何处理数据库连接、查询执行、结果集读取和文件输出流的全过程。

被折叠的 条评论
为什么被折叠?



