jdbc中大对象(图片,影音)的读写

来源:互联网 发布:epub转txt软件 编辑:程序博客网 时间:2024/05/02 03:01

       以前存大对象(图片,影音)都是存的路径,今天一个case要求将对象存入数据库(sqlserver,比oracle差一点,oracle可以很好存取大对象),弄了半天,终于搞定了:

数据库:

create table picture

(

    id int  identity(1,1) primary key,

   pic image

)

程序代码:

import java.sql.DriverManager;
import java.sql.SQLException;


import java.sql.*;
import java.io.*;
public class PicTest {
 public static java.sql.Connection getConnectin() throws ClassNotFoundException,SQLException
 {
  Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
  java.sql.Connection con=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=pubs","sa","");
  return con;
 }
 /**
  * @param args
  */
 public static void main1(String[] args) {
  // TODO Auto-generated method stub
  try {
   java.sql.Connection con=PicTest.getConnectin();
   PreparedStatement pst=con.prepareStatement("insert into pic values(?)");
   FileInputStream fi=new FileInputStream(new File("D:/Documents and Settings/hanwei/My Documents/My Pictures/190.jpg"));
   System.out.println(fi.available());
   pst.setBinaryStream(1, fi, fi.available());
   pst.executeUpdate();
   
   pst.close();
   fi.close();
   con.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch(Exception e)
  {}
 }

 
 public static void main2(String[] args) {
  // TODO Auto-generated method stub
  try {
   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
   java.sql.Connection con=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=pubs","sa","");
   PreparedStatement pst=con.prepareStatement("select * from pic",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
   FileOutputStream fo=new FileOutputStream(new File("c:/1.jpg"));
   ResultSet rs=pst.executeQuery();
   byte []in=null;
   if(rs.next())
   {
    in=rs.getBytes(2);
   }
   fo.write(in);
   pst.close();
   fo.close();
   con.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch(Exception e)
  {}
 }
}

其中main1方法是将图片存入数据库,mian2方法将图片取出来,实际操作中可以将文件后缀也作为一个字段存入数据库,路径作为参数传入;

   时间有限,简单的写了下,贻笑大方.