JDBC将图片保存再数据库

    xiaoxiao2021-03-25  78

    Demo PreparedStatement setBinaryStream

    表结构:

    [sql]  view plain  copy   create table TEST   (     ID  INTEGER,     IMG BLOB   )   [java]  view plain  copy   import java.io.File;   import java.io.FileInputStream;   import java.io.FileNotFoundException;   import java.io.IOException;   import java.sql.Connection;   import java.sql.DriverManager;   import java.sql.PreparedStatement;   import java.sql.SQLException;      public class Test {              static {           try {               Class.forName("oracle.jdbc.driver.OracleDriver");           } catch (ClassNotFoundException e) {               e.printStackTrace();           }       }          /**       * 获得Connection       *        * @return       */       public static Connection getConnection() {           Connection conn = null;           try {               conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/orcl""root""root");           } catch (SQLException e) {               e.printStackTrace();           }           return conn;       }          public static void main(String[] args) {           // TODO Auto-generated method stub           PreparedStatement pst = null;           FileInputStream fis=null;           File file = new File("d:\\image.jpg");           Connection conn = getConnection();           String sql = "insert into test(id,img) values('1',?)";           try {               pst = conn.prepareStatement(sql);               fis=new FileInputStream(file);               pst.setBinaryStream(1, fis, fis.available());               pst.executeUpdate();           } catch (SQLException e) {               e.printStackTrace();           } catch (FileNotFoundException e) {               e.printStackTrace();           } catch (IOException e) {               e.printStackTrace();           }                      // 省略IO流close       }      }   pst.setBinaryStream(1, fis, fis.available());

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

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

    转载请注明原文地址: https://ju.6miu.com/read-19507.html

    最新回复(0)