- import java.sql.*;
- import java.io.*;
- public class binarydata {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- read();
- //create();
- }
- public static void create()
- {
- Connection ct=null;
- PreparedStatement ps=null;
- ResultSet rs=null;
- try
- {
- ct=JDBCUtils.getConnection();
- String sql="insert into picture(picture)values(?)";
- ps=ct.prepareStatement(sql);
- InputStream in=new BufferedInputStream(new FileInputStream(new File("1.png")));
- ps.setBinaryStream(1, in);
- int i=ps.executeUpdate();
- System.out.println("i="+i);
- in.close();
- }catch(Exception e)
- {
- e.printStackTrace();
- }finally
- {
- JDBCUtils.free(rs, ps, ct);
- }
- }
-
- public static void read()
- {
- Connection ct=null;
- PreparedStatement ps=null;
- ResultSet rs=null;
- try
- {
- ct=JDBCUtils.getConnection();
- String sql="select picture from picture";
- ps=ct.prepareStatement(sql);
- rs=ps.executeQuery();
- int m=0;
- while(rs.next())
- {
-
- InputStream in=rs.getBinaryStream("picture");
- OutputStream out=new BufferedOutputStream(new FileOutputStream(new File("D://"+(m++)+".png")));
- byte[] buf=new byte[1024];
- int i=0;
- while((i=in.read(buf))!=-1)
- {
- out.write(buf,0,i);
- }
- in.close();
- out.close();
- }
- }catch(Exception e)
- {
- e.printStackTrace();
- }finally
- {
- JDBCUtils.free(rs, ps, ct);
- }
- }
- }
复制代码
工具类:
- import java.sql.*;
- public class JDBCUtils {
- private static String url="jdbc:mysql://localhost:3306/user";
- private static String user="root";
- private static String password="root";
-
- private JDBCUtils(){}
-
- static
- {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- public static Connection getConnection() throws SQLException
- {
- return DriverManager.getConnection(url,user,password);
- }
-
- public static void free(ResultSet rs,Statement st,Connection ct)
- {
- try
- {
- if(rs!=null)
- rs.close();
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- if(st!=null)
- st.close();
- }catch(Exception e)
- {
- e.printStackTrace();
- }finally
- {
- if(ct!=null)
- try {
- ct.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码
|