当前位置: 首页 > >

java从数据库中读取图片文件

发布时间:

附属程序: package com.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Connec { Connection con=null; public Connec(){ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//加载数据库驱 动(此驱动为 jdbc:odbc 驱动) } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { con=DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databasename=star","sa ","sa");//连接数据库,star 数据库名,sa 分别为账户名和密码 if(!con.isClosed()){ System.out.println("ok"); }else{ System.out.println("error"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Connection getCon(){ return con; } }

主程序:
package com.db.main; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream;

import java.io.IOException; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.db.Connec; public class Win { public static void main(String[] args) { // TODO Auto-generated method stub // // @SuppressWarnings("unused") Add add=new Add(); @SuppressWarnings("unused") Connection con=(new Connec()).getCon(); if(con!=null){ System.out.println("连接成功"); } try { FileOutputStream ous=new FileOutputStream(new File("C:\\zz.jpg")); PreparedStatement ps=con.prepareStatement("select Image from Image where name=\'D:\\My Documents\\见证.jpg\'");//从数据库中读取的图片是 事先已经存入的二进制数据 ResultSet rs=ps.executeQuery(); rs.next(); Blob ob=null; ob=rs.getBlob(1); long size=ob.length(); byte bs[]=ob.getBytes(1, (int)size); ous.write(bs); ous.flush(); ous.close(); rs.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace();

} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }




友情链接: