JDBC将图片保存再数据库

来源:互联网 发布:如何解决网络劫持 编辑:程序博客网 时间:2024/05/29 14:01

Demo PreparedStatement setBinaryStream

表结构:

[sql] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. create table TEST  
  2. (  
  3.   ID  INTEGER,  
  4.   IMG BLOB  
  5. )  
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. import java.sql.Connection;  
  6. import java.sql.DriverManager;  
  7. import java.sql.PreparedStatement;  
  8. import java.sql.SQLException;  
  9.   
  10. public class Test {  
  11.       
  12.     static {  
  13.         try {  
  14.             Class.forName("oracle.jdbc.driver.OracleDriver");  
  15.         } catch (ClassNotFoundException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19.   
  20.     /** 
  21.      * 获得Connection 
  22.      *  
  23.      * @return 
  24.      */  
  25.     public static Connection getConnection() {  
  26.         Connection conn = null;  
  27.         try {  
  28.             conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/orcl""root""root");  
  29.         } catch (SQLException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.         return conn;  
  33.     }  
  34.   
  35.     public static void main(String[] args) {  
  36.         // TODO Auto-generated method stub  
  37.         PreparedStatement pst = null;  
  38.         FileInputStream fis=null;  
  39.         File file = new File("d:\\image.jpg");  
  40.         Connection conn = getConnection();  
  41.         String sql = "insert into test(id,img) values('1',?)";  
  42.         try {  
  43.             pst = conn.prepareStatement(sql);  
  44.             fis=new FileInputStream(file);  
  45.             pst.setBinaryStream(1, fis, fis.available());  
  46.             pst.executeUpdate();  
  47.         } catch (SQLException e) {  
  48.             e.printStackTrace();  
  49.         } catch (FileNotFoundException e) {  
  50.             e.printStackTrace();  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.           
  55.         // 省略IO流close  
  56.     }  
  57.   
  58. }  
pst.setBinaryStream(1, fis, fis.available());

三个参数分别为:参数索引,流对象,流对象大小 


转自http://blog.csdn.net/itmyhome1990/article/details/41824447

0 0