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

  显示原文与译文双语对照的内容
0 0

我正在尝试上传以下代码,但该文件未被上传。 控制台仍然显示消息"1 记录已经成功插入。"

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();
 }
 }
}
时间:原作者:5个回答

0 0

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

以下是验证数据库( 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();
 }
}
原作者:
...