如何在数据库中上传文件?

时间:2014-07-07 03:20:04

标签: java sql

我正在尝试使用下面的代码上传图像文件,但文件未上传。控制台仍显示消息“1 Record Successfully Inserted。”

Create table image
(
   name varchar2(20),
   photo blob
);

import java.sql.*;
import java.io.*;

public class ImageWriter {

    static Connection connection = null;
    static CallableStatement pstat = null;
    static String connectionURL = null;

    public static void main(String[] args) {
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "SYSTEM", "SYSTEM");

            PreparedStatement pstat = connection.prepareStatement("insert into image(name,photo) values(?,?)");

            FileInputStream fin = new FileInputStream("E:\\test.jpg");
            pstat.setString(1, "ABC");
            pstat.setBinaryStream(2, fin,fin.available());

            int result = pstat.executeUpdate();
            System.out.println(result + " Record Successfully Inserted");

            connection.close();

        }
        catch(Exception e){
            e.printStackTrace();
        }

    }

}

1 个答案:

答案 0 :(得分:0)

上面的代码工作正常。 我不知道你是如何验证数据库的内容的。

这是验证db(blob列)的代码:尝试使用此方法。我用你的代码插入图像,我可以成功检索图像。 (注意:文件扩展名应该相同)

public static void getPic() {
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:orcl", "sys as sysdba",
                "Oracle123");

        ResultSet rs = null;
        Statement stmt = null;
        oracle.sql.BLOB photo = null;
        conn.setAutoCommit(false);
        stmt = conn.createStatement();
        String name="ABC";
        rs = stmt.executeQuery("select photo from  image where name = '" + name + "'" );
        rs.next();
        photo = ((OracleResultSet) rs).getBLOB(1);
        File f = new File("E:/image2.jpg");
        f.getParentFile().mkdirs(); 
        f.createNewFile();
        InputStream in = photo.getBinaryStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OutputStream outputStream = new FileOutputStream(f);
        int bufferSize = 1024;
        int length = (int) photo.length();
        byte[] buffer = new byte[bufferSize];
        while((length = in.read(buffer)) != -1) {
            out.write(buffer,0,length);
        }
        out.writeTo(outputStream);
        System.out.println("Image Retrieved");
        out.close();
        rs.close();
        stmt.close();
        conn.close();

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}